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 | reset use statements order | 589fe7968349b191395547b9a0c5044a22d4456f | <ide><path>src/Illuminate/Http/Client/Factory.php
<ide> namespace Illuminate\Http\Client;
<ide>
<ide> use Closure;
<add>use function GuzzleHttp\Promise\promise_for;
<ide> use GuzzleHttp\Psr7\Response as Psr7Response;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use PHPUnit\Framework\Assert as PHPUnit;
<ide>
<del>use function GuzzleHttp\Promise\promise_for;
<del>
<ide> /**
<ide> * @method \Illuminate\Http\Client\PendingRequest accept(string $contentType)
<ide> * @method \Illuminate\Http\Client\PendingRequest acceptJson() | 1 |
Javascript | Javascript | add a test case for the path.posix.resolve | e3555e9c2b2877d1214474647a6bae6207046bfb | <ide><path>test/parallel/test-path-resolve.js
<ide> if (common.isWindows) {
<ide> const resolvedPath = spawnResult.stdout.toString().trim();
<ide> assert.strictEqual(resolvedPath.toLowerCase(), process.cwd().toLowerCase());
<ide> }
<add>
<add>if (!common.isWindows) {
<add> // Test handling relative paths to be safe when process.cwd() fails.
<add> process.cwd = () => '';
<add> assert.strictEqual(process.cwd(), '');
<add> const resolved = path.resolve();
<add> const expected = '.';
<add> assert.strictEqual(resolved, expected);
<add>} | 1 |
Text | Text | add initial draft of converting your package | 7a0b8c31d497ccaf4e590a794276bdbbfd0299e8 | <ide><path>docs/upgrading/upgrading-your-package.md
<add># Upgrading your package to 1.0 APIs
<add>
<add>Atom is rapidly approaching 1.0. Much of the effort leading up to the 1.0 has been cleaning up APIs in an attempt to future proof, and make a more pleasant experience developing packages.
<add>
<add>This document will guide you through the large bits of upgrading your package to work with 1.0 APIs.
<add>
<add>## Deprecations
<add>
<add>All of the methods that have changes emit deprecation messages when called. These messages are shown in two places: your package specs, and in Deprecation Cop.
<add>
<add>### Specs
<add>
<add>Just run your specs, and all the deprecations will be displayed in yellow.
<add>
<add>TODO: image of deprecations in specs
<add>
<add>### Deprecation Cop
<add>
<add>Run an atom window in dev mode (`atom -d`) with your package loaded, and open Deprecation Cop (search for `deprecation` in the command palette).
<add>
<add>TODO: image of deprecations in DepCop
<add>
<add>## Views
<add>
<add>### The Old
<add>
<add>Previous to 1.0, views in packages were baked into Atom core. These views were based on jQuery and `space-pen`. They look something like this:
<add>
<add>```coffee
<add>{$, TextEditorView, View} = require 'atom'
<add>
<add>module.exports =
<add>class SomeView extends View
<add> @content: ->
<add> @div class: 'find-and-replace', =>
<add> @div class: 'block', =>
<add> @subview 'myEditor', new TextEditorView(mini: true)
<add> #...
<add>```
<add>
<add>Requiring `atom` used to provide the following view helpers:
<add>
<add>```
<add>$
<add>$$
<add>$$$
<add>View
<add>TextEditorView
<add>ScrollView
<add>SelectListView
<add>Workspace
<add>WorkspaceView
<add>```
<add>
<add>### The New
<add>
<add>Atom no longer provides these view helpers baked in. They are now available from two npm packages: `space-pen`, and `atom-space-pen-views`
<add>
<add>`space-pen` now provides
<add>
<add>```
<add>$
<add>$$
<add>$$$
<add>View
<add>```
<add>
<add>`atom-space-pen-views` now provides
<add>
<add>```
<add>TextEditorView
<add>ScrollView
<add>SelectListView
<add>```
<add>
<add>`Workspace` and `WorkspaceView` are _no longer provided_ in any capacity. They should be unnecessary
<add>
<add>#### jQuery
<add>
<add>If you do not need `space-pen`, you can require jQuery directly. In your `package.json` add this to the `dependencies` object:
<add>
<add>```js
<add>"jquery": "^2"
<add>```
<add>
<add>#### NPM dependencies
<add>
<add>```js
<add>{
<add> "dependencies": {
<add> "jquery": "^2" // if you want to include jquery directly
<add> "space-pen": "^3"
<add> "atom-space-pen-views": "^0"
<add> }
<add>}
<add>```
<add>
<add>#### Converting your views
<add>
<add>Sometimes it should be as simple as converting the requires at the top of each view page. In the case of our above example, you can just convert them to the following:
<add>
<add>```coffee
<add>{$, View} = require 'space-pen'
<add>{TextEditorView} = require 'atom-space-pen-views'
<add>```
<add>
<add>## Specs
<add>
<add>TODO: come up with patterns for | 1 |
Mixed | Ruby | prevent double save of cyclic associations | a1a5d37749964b1e1a23914ef13da327403e34cb | <ide><path>activerecord/CHANGELOG.md
<add>* Prevent double saves in autosave of cyclic associations
<add>
<add> Adds a @saving state which tracks if a record is currently being saved.
<add> If @saving is set to true, the record won't be saved by the autosave callbacks.
<add>
<add> *Petrik de Heus*
<add>
<ide> * Fix Float::INFINITY assignment to datetime column with postgresql adapter
<ide>
<ide> Before:
<ide><path>activerecord/lib/active_record/autosave_association.rb
<ide> def define_autosave_validation_callbacks(reflection)
<ide> def reload(options = nil)
<ide> @marked_for_destruction = false
<ide> @destroyed_by_association = nil
<add> @saving = false
<ide> super
<ide> end
<ide>
<add> def save(**options) # :nodoc
<add> saving { super }
<add> end
<add>
<add> def save!(**options) # :nodoc:
<add> saving { super }
<add> end
<add>
<ide> # Marks this record to be destroyed as part of the parent's save transaction.
<ide> # This does _not_ actually destroy the record instantly, rather child record will be destroyed
<ide> # when <tt>parent.save</tt> is called.
<ide> def changed_for_autosave?
<ide> new_record? || has_changes_to_save? || marked_for_destruction? || nested_records_changed_for_autosave?
<ide> end
<ide>
<add> # Returns whether or not this record is already being saved outside of the
<add> # current autosave callback
<add> def saving?
<add> @saving
<add> end
<add>
<add> def can_save? #:nodoc:
<add> !destroyed? && !saving?
<add> end
<add>
<ide> private
<add> # Track if this record is being saved. If it is being saved we
<add> # can skip saving it in the autosave callbacks
<add> def saving
<add> previously_saving, @saving = @saving, true
<add> yield
<add> ensure
<add> @saving = previously_saving
<add> end
<add>
<ide> # Returns the record for an association collection that should be validated
<ide> # or saved. If +autosave+ is +false+ only new records will be returned,
<ide> # unless the parent is/was a new record itself.
<ide> def save_collection_association(reflection)
<ide> end
<ide>
<ide> records.each do |record|
<del> next if record.destroyed?
<add> next unless record.can_save?
<ide>
<ide> saved = true
<ide>
<ide> def save_has_one_association(reflection)
<ide> association = association_instance_get(reflection.name)
<ide> record = association && association.load_target
<ide>
<del> if record && !record.destroyed?
<add> if record&.can_save?
<ide> autosave = reflection.options[:autosave]
<ide>
<ide> if autosave && record.marked_for_destruction?
<ide> def save_belongs_to_association(reflection)
<ide> return unless association && association.loaded? && !association.stale_target?
<ide>
<ide> record = association.load_target
<del> if record && !record.destroyed?
<add> if record&.can_save?
<ide> autosave = reflection.options[:autosave]
<ide>
<ide> if autosave && record.marked_for_destruction?
<ide><path>activerecord/lib/active_record/core.rb
<ide> def init_internals
<ide> @previously_new_record = false
<ide> @destroyed = false
<ide> @marked_for_destruction = false
<add> @saving = false
<ide> @destroyed_by_association = nil
<ide> @_start_transaction_state = nil
<ide> @strict_loading = self.class.strict_loading_by_default
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def restore_transaction_record_state(force_restore_state = false)
<ide> attr = attr.with_value_from_user(value) if attr.value != value
<ide> attr
<ide> end
<add> @saving = false
<ide> @mutations_from_database = nil
<ide> @mutations_before_last_save = nil
<ide> if @attributes.fetch_value(@primary_key) != restore_state[:id]
<ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb
<ide> def test_circular_autosave_association_correctly_saves_multiple_records
<ide> fall.sections << sections
<ide> fall.save!
<ide> fall.reload
<del> assert_equal sections, fall.sections.sort_by(&:id)
<add> assert_equal sections.sort_by(&:id), fall.sections.sort_by(&:id)
<ide> end
<ide>
<ide> private
<ide><path>activerecord/test/cases/autosave_association_test.rb
<ide> def test_should_update_children_when_association_redefined_in_subclass
<ide> assert_equal "Updated", valid_project.name
<ide> end
<ide> end
<add>
<add>class TestCyclicAutosaveAssociationsOnlySaveOnce < ActiveRecord::TestCase
<add> teardown do
<add> $autosave_saving_stack = []
<add> end
<add>
<add> test "child is saved only once if child is the inverse has_one of parent" do
<add> ship_reflection = Ship.reflect_on_association(:pirate)
<add> pirate_reflection = Pirate.reflect_on_association(:ship)
<add> assert_equal ship_reflection, pirate_reflection.inverse_of, "The pirate reflection's inverse should be the ship reflection"
<add>
<add> child = Ship.new(name: "Nights Dirty Lightning")
<add> parent = child.build_pirate(catchphrase: "Aye")
<add> child.save!
<add> assert child.previously_new_record?
<add> assert parent.previously_new_record?
<add> end
<add>
<add> test "child is saved only once if child is an inverse has_many of parent" do
<add> child = FamousShip.new(name: "Poison Orchid")
<add> parent = child.build_famous_pirate(catchphrase: "Aye")
<add> child.save!
<add> assert child.previously_new_record?
<add> assert parent.previously_new_record?
<add> end
<add>
<add> test "similar children are saved in the autosave" do
<add> child1 = FamousShip.new(name: "Poison Orchid")
<add> parent = child1.build_famous_pirate(catchphrase: "Aye")
<add> child2 = parent.famous_ships.build(name: "Red Messenger")
<add> child1.save!
<add> assert child2.persisted?
<add> assert child1.previously_new_record?
<add> assert parent.previously_new_record?
<add> assert_equal [child2, child1], parent.reload.famous_ships
<add> end
<add>
<add> test "parent is saved only once" do
<add> child = Ship.new(name: "Nights Dirty Lightning")
<add> parent = child.build_pirate(catchphrase: "Aye")
<add> parent.save!
<add> assert child.previously_new_record?
<add> assert parent.previously_new_record?
<add> end
<add>
<add> test "saving? is reset to false if validations fail" do
<add> child = Ship.new(name: "Nights Dirty Lightning")
<add> child.build_pirate
<add> assert_not child.save
<add> assert_not_predicate child, :saving?
<add> end
<add>
<add> test "saving? is set to false after multiple nested saves" do
<add> ship_with_saving_stack = Class.new(Ship) do
<add> before_save { $autosave_saving_stack << saving? }
<add> after_save { $autosave_saving_stack << saving? }
<add> end
<add>
<add> pirate_with_callbacks = Class.new(Pirate) do
<add> after_save { ship.save }
<add> after_create { ship.save }
<add> after_commit { ship.save }
<add> end
<add>
<add> child = ship_with_saving_stack.new(name: "Nights Dirty Lightning")
<add> child.pirate = pirate_with_callbacks.new(catchphrase: "Aye")
<add> $autosave_saving_stack = []
<add> child.save!
<add> assert_equal [true] * 8, $autosave_saving_stack
<add> assert_equal false, child.saving?
<add> end
<add>end | 6 |
Javascript | Javascript | flow type touchablehighlight | f0c18dc820537892dcc33d5aebbf4f52cf299b95 | <ide><path>Libraries/Components/Touchable/TouchableHighlight.js
<ide> const createReactClass = require('create-react-class');
<ide> const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
<ide>
<ide> import type {PressEvent} from 'CoreEventTypes';
<add>import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback';
<add>import type {ViewStyleProp} from 'StyleSheet';
<add>import type {ColorValue} from 'StyleSheetTypes';
<ide>
<ide> const DEFAULT_PROPS = {
<ide> activeOpacity: 0.85,
<ide> const DEFAULT_PROPS = {
<ide>
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide>
<add>type IOSProps = $ReadOnly<{|
<add> hasTVPreferredFocus?: ?boolean,
<add> tvParallaxProperties?: ?Object,
<add>|}>;
<add>
<add>type Props = $ReadOnly<{|
<add> ...TouchableWithoutFeedbackProps,
<add> ...IOSProps,
<add>
<add> activeOpacity?: ?number,
<add> underlayColor?: ?ColorValue,
<add> style?: ?ViewStyleProp,
<add> onShowUnderlay?: ?Function,
<add> onHideUnderlay?: ?Function,
<add> testOnly_pressed?: ?boolean,
<add>|}>;
<add>
<ide> /**
<ide> * A wrapper for making views respond properly to touches.
<ide> * On press down, the opacity of the wrapped view is decreased, which allows
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide> *
<ide> */
<ide>
<del>const TouchableHighlight = createReactClass({
<add>const TouchableHighlight = ((createReactClass({
<ide> displayName: 'TouchableHighlight',
<ide> propTypes: {
<ide> ...TouchableWithoutFeedback.propTypes,
<ide> const TouchableHighlight = createReactClass({
<ide> </View>
<ide> );
<ide> },
<del>});
<add>}): any): React.ComponentType<Props>);
<ide>
<ide> module.exports = TouchableHighlight;
<ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js
<ide> const EdgeInsetsPropType = require('EdgeInsetsPropType');
<ide> const React = require('React');
<ide> const PropTypes = require('prop-types');
<del>/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
<del> * found when Flow v0.54 was deployed. To see the error delete this comment and
<del> * run Flow. */
<ide> const TimerMixin = require('react-timer-mixin');
<ide> const Touchable = require('Touchable');
<ide>
<ide> const createReactClass = require('create-react-class');
<ide> const ensurePositiveDelayProps = require('ensurePositiveDelayProps');
<del>/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
<del> * found when Flow v0.54 was deployed. To see the error delete this comment and
<del> * run Flow. */
<ide> const warning = require('fbjs/lib/warning');
<ide>
<ide> const {
<ide> import type {PressEvent} from 'CoreEventTypes';
<ide> import type {EdgeInsetsProp} from 'EdgeInsetsPropType';
<ide> import type {
<ide> AccessibilityComponentType,
<del> AccessibilityTrait,
<add> AccessibilityTraits as AccessibilityTraitsFlow,
<ide> } from 'ViewAccessibility';
<ide>
<ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
<ide>
<del>type Props = $ReadOnly<{|
<del> accessible?: boolean,
<del> accessibilityComponentType?: AccessibilityComponentType,
<add>export type Props = $ReadOnly<{|
<add> accessible?: ?boolean,
<add> accessibilityComponentType?: ?AccessibilityComponentType,
<ide> accessibilityLabel?:
<ide> | null
<ide> | React$PropType$Primitive<any>
<ide> | string
<ide> | Array<any>
<ide> | any,
<del> accessibilityTraits?: AccessibilityTrait | Array<AccessibilityTrait>,
<add> accessibilityTraits?: ?AccessibilityTraitsFlow,
<ide> children?: ?React.Node,
<ide> delayLongPress?: ?number,
<ide> delayPressIn?: ?number,
<ide><path>Libraries/Components/View/ViewAccessibility.js
<ide> export type AccessibilityTrait =
<ide> | 'allowsDirectInteraction'
<ide> | 'pageTurn';
<ide>
<add>export type AccessibilityTraits =
<add> | AccessibilityTrait
<add> | $ReadOnlyArray<AccessibilityTrait>;
<add>
<ide> export type AccessibilityComponentType =
<ide> | 'none'
<ide> | 'button'
<ide><path>RNTester/js/RNTesterExampleList.js
<ide> class RowComponent extends React.PureComponent<{
<ide> render() {
<ide> const {item} = this.props;
<ide> return (
<del> <TouchableHighlight {...this.props} onPress={this._onPress}>
<add> <TouchableHighlight
<add> onShowUnderlay={this.props.onShowUnderlay}
<add> onHideUnderlay={this.props.onHideUnderlay}
<add> onPress={this._onPress}>
<ide> <View style={styles.row}>
<ide> <Text style={styles.rowTitleText}>{item.module.title}</Text>
<ide> <Text style={styles.rowDetailText}>{item.module.description}</Text>
<ide><path>RNTester/js/TouchableExample.js
<ide> exports.examples = [
<ide> <TouchableHighlight
<ide> style={styles.wrapper}
<ide> activeOpacity={1}
<del> animationVelocity={0}
<ide> tvParallaxProperties={{
<ide> pressMagnification: 1.3,
<ide> pressDuration: 0.6,
<ide> class TouchableDisabled extends React.Component<{}> {
<ide> <TouchableHighlight
<ide> activeOpacity={1}
<ide> disabled={true}
<del> animationVelocity={0}
<ide> underlayColor="rgb(210, 230, 255)"
<ide> style={[styles.row, styles.block]}
<ide> onPress={() => console.log('custom THW text - highlight')}>
<ide> class TouchableDisabled extends React.Component<{}> {
<ide>
<ide> <TouchableHighlight
<ide> activeOpacity={1}
<del> animationVelocity={0}
<ide> underlayColor="rgb(210, 230, 255)"
<ide> style={[styles.row, styles.block]}
<ide> onPress={() => console.log('custom THW text - highlight')}> | 5 |
Javascript | Javascript | resolve the char->glyphs mapping issue | 3dbfde89a34796ff8060738f38a227d70be27580 | <ide><path>PDFFont.js
<ide> var fontCount = 0;
<ide> var Fonts = {
<ide> _active: null,
<ide> get active() {
<del> return this._active || { encoding: {} };
<add> return this._active || { encoding: [] };
<ide> },
<ide>
<ide> set active(aName) {
<ide><path>pdf.js
<ide> var Lexer = (function() {
<ide> }
<ide> }
<ide>
<del> x = Fonts.unicodeFromCode(x);
<ide> str += String.fromCharCode(x);
<ide> break;
<ide> case '\r':
<ide> var Lexer = (function() {
<ide> }
<ide> break;
<ide> default:
<del> var unicode = Fonts.unicodeFromCode(ch.charCodeAt(0));
<del> str += String.fromCharCode(unicode);
<add> str += ch;
<ide> break;
<ide> }
<ide> } while (!done);
<ide> var CanvasGraphics = (function() {
<ide> var descriptor = xref.fetch(fontDict.get("FontDescriptor"));
<ide> var fontName = descriptor.get("FontName").name;
<ide> fontName = fontName.replace("+", "_");
<del>
<add>
<ide> var font = Fonts[fontName];
<ide> if (!font) {
<ide> var fontFile = descriptor.get2("FontFile", "FontFile2");
<ide> var CanvasGraphics = (function() {
<ide> for (var j = 0; j < widths.length; j++) {
<ide> var index = widths[j];
<ide> if (index)
<del> charset.push(encoding[j + firstchar]);
<add> charset.push(encoding[j + firstchar]);
<ide> }
<ide> }
<ide> }
<ide> var CanvasGraphics = (function() {
<ide> this.ctx.scale(1, -1);
<ide> this.ctx.transform.apply(this.ctx, this.current.textMatrix);
<ide>
<del> this.ctx.fillText(text, this.current.x, this.current.y);
<add> // Replace characters code by glyphs code
<add> var glyphs = [];
<add> for (var i = 0; i < text.length; i++)
<add> glyphs[i] = String.fromCharCode(Fonts.unicodeFromCode(text[i].charCodeAt(0)));
<add>
<add> this.ctx.fillText(glyphs.join(""), this.current.x, this.current.y);
<ide> this.current.x += this.ctx.measureText(text).width;
<ide>
<ide> this.ctx.restore();
<ide><path>test.js
<ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
<ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
<ide>
<del>var pdfDocument, canvas, pageDisplay, pageNum, pageTimeout;
<add>var pdfDocument, canvas, pageDisplay, pageNum, pageInterval;
<ide> function load() {
<ide> canvas = document.getElementById("canvas");
<ide> canvas.mozOpaque = true;
<ide> function gotoPage(num) {
<ide>
<ide> function displayPage(num) {
<ide> if (pageNum != num)
<del> window.clearTimeout(pageTimeout);
<add> window.clearTimeout(pageInterval);
<ide>
<ide> document.getElementById("pageNumber").value = num;
<ide>
<ide> function displayPage(num) {
<ide> var page = pdfDocument.getPage(pageNum = num);
<ide>
<ide> var t1 = Date.now();
<del>
<ide> var ctx = canvas.getContext("2d");
<ide> ctx.save();
<ide> ctx.fillStyle = "rgb(255, 255, 255)";
<ide> function displayPage(num) {
<ide> page.compile(gfx, fonts);
<ide> var t2 = Date.now();
<ide>
<del> var interval = setInterval(function() {
<add> // FIXME This need to be replaced by an event
<add> pageInterval = setInterval(function() {
<ide> for (var i = 0; i < fonts.length; i++) {
<ide> if (fonts[i].loading)
<ide> return;
<ide> }
<add> var t3 = Date.now();
<ide>
<add> clearInterval(pageInterval);
<ide> page.display(gfx);
<del> var t3 = Date.now();
<add>
<add> var t4 = Date.now();
<add>
<ide> var infoDisplay = document.getElementById("info");
<del> infoDisplay.innerHTML = "Time to load/compile/render: "+ (t1 - t0) + "/" + (t2 - t1) + "/" + (t3 - t2) + " ms";
<del> clearInterval(interval);
<add> infoDisplay.innerHTML = "Time to load/compile/fonts/render: "+ (t1 - t0) + "/" + (t2 - t1) + "/" + (t3 - t2) + "/" + (t4 - t3) + " ms";
<ide> }, 10);
<ide> }
<ide> | 3 |
PHP | PHP | remove remaining priorities. | 19fcecfc782cb7fe0dea6f8a293e167cfb1bf38d | <ide><path>src/Illuminate/Contracts/View/Factory.php
<ide> public function share($key, $value = null);
<ide> *
<ide> * @param array|string $views
<ide> * @param \Closure|string $callback
<del> * @param int|null $priority
<ide> * @return array
<ide> */
<del> public function composer($views, $callback, $priority = null);
<add> public function composer($views, $callback);
<ide>
<ide> /**
<ide> * Register a view creator event.
<ide><path>src/Illuminate/View/Concerns/ManagesEvents.php
<ide> public function composers(array $composers)
<ide> *
<ide> * @param array|string $views
<ide> * @param \Closure|string $callback
<del> * @param int|null $priority
<ide> * @return array
<ide> */
<del> public function composer($views, $callback, $priority = null)
<add> public function composer($views, $callback)
<ide> {
<ide> $composers = [];
<ide>
<ide> foreach ((array) $views as $view) {
<del> $composers[] = $this->addViewEvent($view, $callback, 'composing: ', $priority);
<add> $composers[] = $this->addViewEvent($view, $callback, 'composing: ');
<ide> }
<ide>
<ide> return $composers;
<ide> public function composer($views, $callback, $priority = null)
<ide> * @param string $view
<ide> * @param \Closure|string $callback
<ide> * @param string $prefix
<del> * @param int|null $priority
<ide> * @return \Closure|null
<ide> */
<del> protected function addViewEvent($view, $callback, $prefix = 'composing: ', $priority = null)
<add> protected function addViewEvent($view, $callback, $prefix = 'composing: ')
<ide> {
<ide> $view = $this->normalizeName($view);
<ide>
<ide> if ($callback instanceof Closure) {
<del> $this->addEventListener($prefix.$view, $callback, $priority);
<add> $this->addEventListener($prefix.$view, $callback);
<ide>
<ide> return $callback;
<ide> } elseif (is_string($callback)) {
<del> return $this->addClassEvent($view, $callback, $prefix, $priority);
<add> return $this->addClassEvent($view, $callback, $prefix);
<ide> }
<ide> }
<ide>
<ide> protected function addViewEvent($view, $callback, $prefix = 'composing: ', $prio
<ide> * @param string $view
<ide> * @param string $class
<ide> * @param string $prefix
<del> * @param int|null $priority
<ide> * @return \Closure
<ide> */
<del> protected function addClassEvent($view, $class, $prefix, $priority = null)
<add> protected function addClassEvent($view, $class, $prefix)
<ide> {
<ide> $name = $prefix.$view;
<ide>
<ide> protected function addClassEvent($view, $class, $prefix, $priority = null)
<ide> $class, $prefix
<ide> );
<ide>
<del> $this->addEventListener($name, $callback, $priority);
<add> $this->addEventListener($name, $callback);
<ide>
<ide> return $callback;
<ide> }
<ide> protected function classEventMethodForPrefix($prefix)
<ide> *
<ide> * @param string $name
<ide> * @param \Closure $callback
<del> * @param int|null $priority
<ide> * @return void
<ide> */
<del> protected function addEventListener($name, $callback, $priority = null)
<add> protected function addEventListener($name, $callback)
<ide> {
<del> if (is_null($priority)) {
<del> $this->events->listen($name, $callback);
<del> } else {
<del> $this->events->listen($name, $callback, $priority);
<del> }
<add> $this->events->listen($name, $callback);
<ide> }
<ide>
<ide> /**
<ide><path>tests/View/ViewFactoryTest.php
<ide> public function testComposersAreProperlyRegistered()
<ide> $this->assertEquals('bar', $callback());
<ide> }
<ide>
<del> public function testComposersAreProperlyRegisteredWithPriority()
<del> {
<del> $factory = $this->getFactory();
<del> $factory->getDispatcher()->shouldReceive('listen')->once()->with('composing: foo', m::type('Closure'), 1);
<del> $callback = $factory->composer('foo', function () {
<del> return 'bar';
<del> }, 1);
<del> $callback = $callback[0];
<del>
<del> $this->assertEquals('bar', $callback());
<del> }
<del>
<ide> public function testComposersCanBeMassRegistered()
<ide> {
<ide> $factory = $this->getFactory(); | 3 |
Javascript | Javascript | add beta.freecodecamp.com to csp script source | dbe50a5dfa16a5ad5cb5da4e0b2efb2f1902dc4f | <ide><path>server/server.js
<ide> app.use(helmet.csp({
<ide> '*.d3js.org',
<ide> 'https://cdn.inspectlet.com/inspectlet.js',
<ide> 'http://cdn.inspectlet.com/inspectlet.js',
<del> 'http://www.freecodecamp.org'
<add> 'http://beta.freecodecamp.com'
<ide> ].concat(trusted),
<ide> 'connect-src': [
<ide> 'vimeo.com' | 1 |
Javascript | Javascript | remove unneeded changes on webglprogram | 5a1f73f2a6fa0d599030f915b44d7e033bc832c2 | <ide><path>src/renderers/webgl/WebGLProgram.js
<ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters,
<ide> var vertexGlsl = prefixVertex + vertexShader;
<ide> var fragmentGlsl = prefixFragment + fragmentShader;
<ide>
<del> var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl, renderer.debug.checkShaderErrors );
<del> var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl, renderer.debug.checkShaderErrors );
<add> // console.log( '*VERTEX*', vertexGlsl );
<add> // console.log( '*FRAGMENT*', fragmentGlsl );
<add>
<add> var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
<add> var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
<ide>
<ide> gl.attachShader( program, glVertexShader );
<ide> gl.attachShader( program, glFragmentShader ); | 1 |
Python | Python | use current result serializer instead of pickle | 65ca6bcdd919fce57d1de83ffd80c4236dea7b74 | <ide><path>celery/backends/cassandra.py
<ide>
<ide> from celery.backends.base import BaseDictBackend
<ide> from celery.exceptions import ImproperlyConfigured
<del>from celery.utils.serialization import pickle
<ide> from celery.utils.timeutils import maybe_timedelta, timedelta_seconds
<ide> from celery import states
<ide>
<ide> def _do_store():
<ide> cf = self._get_column_family()
<ide> date_done = datetime.utcnow()
<ide> meta = {"status": status,
<del> "result": pickle.dumps(result),
<add> "result": self.encode(result),
<ide> "date_done": date_done.strftime('%Y-%m-%dT%H:%M:%SZ'),
<del> "traceback": pickle.dumps(traceback)}
<add> "traceback": self.encode(traceback)}
<ide> cf.insert(task_id, meta,
<ide> ttl=timedelta_seconds(self.expires))
<ide>
<ide> def _do_get():
<ide> meta = {
<ide> "task_id": task_id,
<ide> "status": obj["status"],
<del> "result": pickle.loads(str(obj["result"])),
<add> "result": self.decode(obj["result"]),
<ide> "date_done": obj["date_done"],
<del> "traceback": pickle.loads(str(obj["traceback"])),
<add> "traceback": self.decode(obj["traceback"]),
<ide> }
<ide> except (KeyError, pycassa.NotFoundException):
<ide> meta = {"status": states.PENDING, "result": None} | 1 |
Ruby | Ruby | use realtime to reduce garbage. [adymo] | fa4d5f2dc1e63df9ce289aedea844fe69327241b | <ide><path>actionpack/lib/action_controller/benchmarking.rb
<ide> def render_with_benchmark(options = nil, extra_options = {}, &block)
<ide> db_runtime = ActiveRecord::Base.connection.reset_runtime if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<ide>
<ide> render_output = nil
<del> @rendering_runtime = Benchmark::measure{ render_output = render_without_benchmark(options, extra_options, &block) }.real
<add> @rendering_runtime = Benchmark::realtime{ render_output = render_without_benchmark(options, extra_options, &block) }
<ide>
<ide> if Object.const_defined?("ActiveRecord") && ActiveRecord::Base.connected?
<ide> @db_rt_before_render = db_runtime | 1 |
PHP | PHP | allow session encryption | 7b892e2452006a9cc0c750f09cd55274ae036d06 | <ide><path>config/session.php
<ide>
<ide> 'expire_on_close' => false,
<ide>
<add> /*
<add> |--------------------------------------------------------------------------
<add> | Session Encryption
<add> |--------------------------------------------------------------------------
<add> |
<add> | This option allows you to easily specify that all of your session data
<add> | should be encrypted before it is stored. All encryption will be run
<add> | automatically by Laravel and you can use the Session like normal.
<add> |
<add> */
<add>
<add> 'encrypt' => false,
<add>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Session File Location | 1 |
Javascript | Javascript | add missing cache | 0e62bdb74abf8b27ea0dc31cb2c8ed1fce49d1eb | <ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> * @returns {string | null} an identifier for library inclusion
<ide> */
<ide> libIdent(options) {
<del> return contextify(options.context, this.userRequest);
<add> return contextify(
<add> options.context,
<add> this.userRequest,
<add> options.associatedObjectForCache
<add> );
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | add use_keras_layer flag for fpn | ac739092f50051e08c00377c3595b225b4daa51e | <ide><path>official/vision/configs/decoders.py
<ide> class FPN(hyperparams.Config):
<ide> num_filters: int = 256
<ide> fusion_type: str = 'sum'
<ide> use_separable_conv: bool = False
<add> use_keras_layer: bool = False
<ide>
<ide>
<ide> @dataclasses.dataclass
<ide><path>official/vision/modeling/decoders/fpn.py
<ide> def __init__(
<ide> num_filters: int = 256,
<ide> fusion_type: str = 'sum',
<ide> use_separable_conv: bool = False,
<add> use_keras_layer: bool = False,
<ide> activation: str = 'relu',
<ide> use_sync_bn: bool = False,
<ide> norm_momentum: float = 0.99,
<ide> def __init__(
<ide> concat for feature fusion.
<ide> use_separable_conv: A `bool`. If True use separable convolution for
<ide> convolution in FPN layers.
<add> use_keras_layer: A `bool`. If Ture use keras layers as many as possible.
<ide> activation: A `str` name of the activation function.
<ide> use_sync_bn: A `bool`. If True, use synchronized batch normalization.
<ide> norm_momentum: A `float` of normalization momentum for the moving average.
<ide> def __init__(
<ide> 'num_filters': num_filters,
<ide> 'fusion_type': fusion_type,
<ide> 'use_separable_conv': use_separable_conv,
<add> 'use_keras_layer': use_keras_layer,
<ide> 'activation': activation,
<ide> 'use_sync_bn': use_sync_bn,
<ide> 'norm_momentum': norm_momentum,
<ide> def __init__(
<ide> norm = tf.keras.layers.experimental.SyncBatchNormalization
<ide> else:
<ide> norm = tf.keras.layers.BatchNormalization
<del> activation_fn = tf.keras.layers.Activation(
<del> tf_utils.get_activation(activation))
<add> activation_fn = tf_utils.get_activation(activation, use_keras_layer=True)
<ide>
<ide> # Build input feature pyramid.
<ide> if tf.keras.backend.image_data_format() == 'channels_last':
<ide> def __init__(
<ide> feats = {str(backbone_max_level): feats_lateral[str(backbone_max_level)]}
<ide> for level in range(backbone_max_level - 1, min_level - 1, -1):
<ide> feat_a = spatial_transform_ops.nearest_upsampling(
<del> feats[str(level + 1)], 2)
<add> feats[str(level + 1)], 2, use_keras_layer=use_keras_layer)
<ide> feat_b = feats_lateral[str(level)]
<ide>
<ide> if fusion_type == 'sum':
<del> feats[str(level)] = feat_a + feat_b
<add> if use_keras_layer:
<add> feats[str(level)] = tf.keras.layers.Add()([feat_a, feat_b])
<add> else:
<add> feats[str(level)] = feat_a + feat_b
<ide> elif fusion_type == 'concat':
<del> feats[str(level)] = tf.concat([feat_a, feat_b], axis=-1)
<add> if use_keras_layer:
<add> feats[str(level)] = tf.keras.layers.Concatenate(axis=-1)(
<add> [feat_a, feat_b])
<add> else:
<add> feats[str(level)] = tf.concat([feat_a, feat_b], axis=-1)
<ide> else:
<ide> raise ValueError('Fusion type {} not supported.'.format(fusion_type))
<ide>
<ide> def build_fpn_decoder(
<ide> num_filters=decoder_cfg.num_filters,
<ide> fusion_type=decoder_cfg.fusion_type,
<ide> use_separable_conv=decoder_cfg.use_separable_conv,
<add> use_keras_layer=decoder_cfg.use_keras_layer,
<ide> activation=norm_activation_config.activation,
<ide> use_sync_bn=norm_activation_config.use_sync_bn,
<ide> norm_momentum=norm_activation_config.norm_momentum,
<ide><path>official/vision/modeling/decoders/fpn_test.py
<ide> class FPNTest(parameterized.TestCase, tf.test.TestCase):
<ide>
<ide> @parameterized.parameters(
<del> (256, 3, 7, False, 'sum'),
<del> (256, 3, 7, True, 'concat'),
<add> (256, 3, 7, False, False, 'sum'),
<add> (256, 3, 7, False, True, 'sum'),
<add> (256, 3, 7, True, False, 'concat'),
<add> (256, 3, 7, True, True, 'concat'),
<ide> )
<ide> def test_network_creation(self, input_size, min_level, max_level,
<del> use_separable_conv, fusion_type):
<add> use_separable_conv, use_keras_layer, fusion_type):
<ide> """Test creation of FPN."""
<ide> tf.keras.backend.set_image_data_format('channels_last')
<ide>
<ide> def test_network_creation(self, input_size, min_level, max_level,
<ide> min_level=min_level,
<ide> max_level=max_level,
<ide> fusion_type=fusion_type,
<del> use_separable_conv=use_separable_conv)
<add> use_separable_conv=use_separable_conv,
<add> use_keras_layer=use_keras_layer)
<ide>
<ide> endpoints = backbone(inputs)
<ide> feats = network(endpoints)
<ide> def test_network_creation(self, input_size, min_level, max_level,
<ide> feats[str(level)].shape.as_list())
<ide>
<ide> @parameterized.parameters(
<del> (256, 3, 7, False),
<del> (256, 3, 7, True),
<add> (256, 3, 7, False, False),
<add> (256, 3, 7, False, True),
<add> (256, 3, 7, True, False),
<add> (256, 3, 7, True, True),
<ide> )
<ide> def test_network_creation_with_mobilenet(self, input_size, min_level,
<del> max_level, use_separable_conv):
<add> max_level, use_separable_conv,
<add> use_keras_layer):
<ide> """Test creation of FPN with mobilenet backbone."""
<ide> tf.keras.backend.set_image_data_format('channels_last')
<ide>
<ide> def test_network_creation_with_mobilenet(self, input_size, min_level,
<ide> input_specs=backbone.output_specs,
<ide> min_level=min_level,
<ide> max_level=max_level,
<del> use_separable_conv=use_separable_conv)
<add> use_separable_conv=use_separable_conv,
<add> use_keras_layer=use_keras_layer)
<ide>
<ide> endpoints = backbone(inputs)
<ide> feats = network(endpoints)
<ide> def test_serialize_deserialize(self):
<ide> num_filters=256,
<ide> fusion_type='sum',
<ide> use_separable_conv=False,
<add> use_keras_layer=False,
<ide> use_sync_bn=False,
<ide> activation='relu',
<ide> norm_momentum=0.99, | 3 |
Javascript | Javascript | add missing argument check | a995a335f4ffbd82c2afc6369f7bc515a3721c27 | <ide><path>lib/javascript/JavascriptParser.js
<ide> class JavascriptParser extends Parser {
<ide> }
<ide> } else if (expr.operator === "-") {
<ide> const argument = this.evaluateExpression(expr.argument);
<del>
<add> if (!argument) return;
<ide> if (argument.isNumber()) {
<ide> const res = new BasicEvaluatedExpression();
<ide> res.setNumber(-argument.number); | 1 |
Javascript | Javascript | use platformtimeout() in more places | d847a744051dc74ca4a595e3b0b04f78892cd4d0 | <ide><path>test/parallel/test-dgram-udp4.js
<ide> server.bind(server_port);
<ide>
<ide> timer = setTimeout(function() {
<ide> throw new Error('Timeout');
<del>}, 200);
<add>}, common.platformTimeout(200));
<ide><path>test/parallel/test-http-1.0.js
<ide> function test(handler, request_generator, response_validator) {
<ide> server.close();
<ide> response_validator(server_response, client_got_eof, true);
<ide> }
<del> var timer = setTimeout(cleanup, 1000);
<add> var timer = setTimeout(cleanup, common.platformTimeout(1000));
<ide> process.on('exit', cleanup);
<ide>
<ide> server.listen(port); | 2 |
Javascript | Javascript | shrink support.js, closes gh-818 | 1ac15582f2a9d45af5a28a9de88d579c8d97bc23 | <ide><path>src/support.js
<ide> jQuery.support = (function() {
<ide> opt,
<ide> input,
<ide> fragment,
<del> tds,
<del> events,
<ide> eventName,
<ide> i,
<ide> isSupported,
<del> div = document.createElement( "div" ),
<del> documentElement = document.documentElement;
<add> div = document.createElement("div");
<ide>
<ide> // Preliminary tests
<del> div.setAttribute("className", "t");
<del> div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
<add> div.setAttribute( "className", "t" );
<add> div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.5;'>a</a><input type='checkbox'/>";
<ide>
<del> all = div.getElementsByTagName( "*" );
<del> a = div.getElementsByTagName( "a" )[ 0 ];
<add> all = div.getElementsByTagName("*");
<add> a = div.getElementsByTagName("a")[ 0 ];
<ide>
<ide> // Can't get basic test support
<ide> if ( !all || !all.length || !a ) {
<ide> return {};
<ide> }
<ide>
<ide> // First batch of supports tests
<del> select = document.createElement( "select" );
<add> select = document.createElement("select");
<ide> opt = select.appendChild( document.createElement("option") );
<del> input = div.getElementsByTagName( "input" )[ 0 ];
<add> input = div.getElementsByTagName("input")[ 0 ];
<ide>
<ide> support = {
<ide> // IE strips leading whitespace when .innerHTML is used
<ide> jQuery.support = (function() {
<ide> // Make sure that element opacity exists
<ide> // (IE uses filter instead)
<ide> // Use a regex to work around a WebKit issue. See #5145
<del> opacity: /^0.55/.test( a.style.opacity ),
<add> opacity: /^0.5/.test( a.style.opacity ),
<ide>
<ide> // Verify style float existence
<ide> // (IE uses styleFloat instead of cssFloat)
<ide> jQuery.support = (function() {
<ide> html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
<ide>
<ide> // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
<del> boxModel: (document.compatMode === "CSS1Compat"),
<add> boxModel: ( document.compatMode === "CSS1Compat" ),
<ide>
<ide> // Will be defined later
<ide> submitBubbles: true,
<ide> jQuery.support = (function() {
<ide> // bound event handlers (IE does this)
<ide> support.noCloneEvent = false;
<ide> });
<del> div.cloneNode( true ).fireEvent( "onclick" );
<add> div.cloneNode( true ).fireEvent("onclick");
<ide> }
<ide>
<ide> // Check if a radio maintains its value
<ide> // after being appended to the DOM
<ide> input = document.createElement("input");
<ide> input.value = "t";
<del> input.setAttribute("type", "radio");
<add> input.setAttribute( "type", "radio" );
<ide> support.radioValue = input.value === "t";
<ide>
<del> input.setAttribute("checked", "checked");
<add> input.setAttribute( "checked", "checked" );
<ide>
<ide> // #11217 - WebKit loses check when the name is after the checked attribute
<ide> input.setAttribute( "name", "t" );
<ide> jQuery.support = (function() {
<ide> // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
<ide> if ( div.attachEvent ) {
<ide> for ( i in {
<del> submit: 1,
<del> change: 1,
<del> focusin: 1
<add> submit: true,
<add> change: true,
<add> focusin: true
<ide> }) {
<ide> eventName = "on" + i;
<ide> isSupported = ( eventName in div );
<ide> jQuery.support = (function() {
<ide> }
<ide> }
<ide>
<del> fragment.removeChild( div );
<del>
<del> // Null elements to avoid leaks in IE
<del> fragment = select = opt = div = input = null;
<del>
<ide> // Run tests that need a body at doc ready
<ide> jQuery(function() {
<del> var container, marginDiv,
<add> var container, div, tds, marginDiv,
<ide> divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
<del> conMarginTop = 1,
<del> boxSizingPrefixes = [ "", "-moz-", "-webkit-", "" ],
<ide> body = document.getElementsByTagName("body")[0];
<ide>
<ide> if ( !body ) {
<ide> jQuery.support = (function() {
<ide> }
<ide>
<ide> container = document.createElement("div");
<del> container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
<add> container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
<ide> body.insertBefore( container, body.firstChild );
<ide>
<ide> // Construct the test element
<ide> jQuery.support = (function() {
<ide> // hidden; don safety goggles and see bug #4512 for more information).
<ide> // (only IE 8 fails this test)
<ide> div.innerHTML = "<table><tr><td style='padding:0;margin:0;border:0;display:none'></td><td>t</td></tr></table>";
<del> tds = div.getElementsByTagName( "td" );
<add> tds = div.getElementsByTagName("td");
<ide> isSupported = ( tds[ 0 ].offsetHeight === 0 );
<ide>
<ide> tds[ 0 ].style.display = "";
<ide> jQuery.support = (function() {
<ide> // (IE <= 8 fail this test)
<ide> support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
<ide>
<del> // Check if div with explicit width and no margin-right incorrectly
<del> // gets computed margin-right based on width of container. For more
<del> // info see bug #3333
<del> // Fails in WebKit before Feb 2011 nightlies
<del> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<add> // Check box-sizing and margin behavior
<add> div.innerHTML = "";
<add> div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;";
<add> support.boxSizing = ( div.offsetWidth === 4 );
<add> support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
<ide> if ( window.getComputedStyle ) {
<del> div.innerHTML = "";
<del> marginDiv = document.createElement( "div" );
<add> support.pixelMargin = ( window.getComputedStyle( div, null ) || {} ).marginTop !== "1%";
<add> support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
<add>
<add> // Check if div with explicit width and no margin-right incorrectly
<add> // gets computed margin-right based on width of container. For more
<add> // info see bug #3333
<add> // Fails in WebKit before Feb 2011 nightlies
<add> // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
<add> marginDiv = document.createElement("div");
<ide> marginDiv.style.cssText = div.style.cssText = divReset;
<ide> marginDiv.style.marginRight = marginDiv.style.width = "0";
<del> div.style.width = "2px";
<add> div.style.width = "1px";
<ide> div.appendChild( marginDiv );
<ide> support.reliableMarginRight =
<del> ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
<add> !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
<ide> }
<ide>
<ide> if ( typeof div.style.zoom !== "undefined" ) {
<ide> jQuery.support = (function() {
<ide> div.style.overflow = "visible";
<ide> div.innerHTML = "<div style='width:5px;'></div>";
<ide> support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
<del> }
<ide>
<del> div.style.cssText = boxSizingPrefixes.join("box-sizing:border-box;") + "border:1px;width:4px;padding:1px;display:block;margin-top:1%;";
<del> support.boxSizing = ( div.offsetWidth === 4 );
<del> if ( window.getComputedStyle ) {
<del> support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
<del> support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
<del> }
<del>
<del> support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
<del>
<del> if ( typeof container.style.zoom !== "undefined" ) {
<ide> container.style.zoom = 1;
<ide> }
<ide>
<add> // Null elements to avoid leaks in IE
<ide> body.removeChild( container );
<del> marginDiv = div = container = null;
<add> container = div = tds = marginDiv = null;
<ide> });
<ide>
<add> // Null elements to avoid leaks in IE
<add> fragment.removeChild( div );
<add> all = a = select = opt = input = fragment = div = null;
<add>
<ide> return support;
<ide> })(); | 1 |
Ruby | Ruby | fix error message for adapternotfound in spec | e47f0da77b59edd20c5d193b52d7966c0125a12a | <ide><path>activerecord/lib/active_record/connection_adapters/connection_specification.rb
<ide> def spec(config)
<ide> adapter_method = "#{spec[:adapter]}_connection"
<ide>
<ide> unless ActiveRecord::Base.respond_to?(adapter_method)
<del> raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
<add> raise AdapterNotFound, "database configuration specifies nonexistent #{spec[:adapter]} adapter"
<ide> end
<ide>
<ide> ConnectionSpecification.new(spec.delete(:name) || "primary", spec, adapter_method)
<ide><path>activerecord/test/cases/connection_specification/resolver_test.rb
<ide> def test_url_invalid_adapter
<ide> assert_match "Could not load the 'ridiculous' Active Record adapter. Ensure that the adapter is spelled correctly in config/database.yml and that you've added the necessary adapter gem to your Gemfile.", error.message
<ide> end
<ide>
<add> def test_error_if_no_adapter_method
<add> error = assert_raises(AdapterNotFound) do
<add> spec "abstract://foo?encoding=utf8"
<add> end
<add>
<add> assert_match "database configuration specifies nonexistent abstract adapter", error.message
<add> end
<add>
<ide> # The abstract adapter is used simply to bypass the bit of code that
<ide> # checks that the adapter file can be required in.
<ide> | 2 |
PHP | PHP | fix method signature in docblock | 3efb9647e0325260e8f1018dae4d00bcf056366a | <ide><path>src/ORM/Query.php
<ide> * @method \Cake\ORM\Table getRepository() Returns the default table object that will be used by this query,
<ide> * that is, the table that will appear in the from clause.
<ide> * @method \Cake\Collection\CollectionInterface each(callable $c) Passes each of the query results to the callable
<del> * @method \Cake\Collection\CollectionInterface sortBy($callback, int $dir) Sorts the query with the callback
<add> * @method \Cake\Collection\CollectionInterface sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC) Sorts the query with the callback
<ide> * @method \Cake\Collection\CollectionInterface filter(callable $c = null) Keeps the results using passing the callable test
<ide> * @method \Cake\Collection\CollectionInterface reject(callable $c) Removes the results passing the callable test
<ide> * @method bool every(callable $c) Returns true if all the results pass the callable test | 1 |
Ruby | Ruby | remove no need `binds.empty?` checking | be0f3179d4458ba3bc8a026469e4acdc1bebd2df | <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def exec_stmt(sql, name, binds, cache_stmt: false)
<ide> type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
<ide>
<ide> log(sql, name, binds) do
<del> if binds.empty? || !cache_stmt
<add> if !cache_stmt
<ide> stmt = @connection.prepare(sql)
<ide> else
<ide> cache = @statements[sql] ||= {
<ide> def exec_stmt(sql, name, binds, cache_stmt: false)
<ide> # place when an error occurs. To support older MySQL versions, we
<ide> # need to close the statement and delete the statement from the
<ide> # cache.
<del> if binds.empty? || !cache_stmt
<add> if !cache_stmt
<ide> stmt.close
<ide> else
<ide> @statements.delete sql
<ide> def exec_stmt(sql, name, binds, cache_stmt: false)
<ide> affected_rows = stmt.affected_rows
<ide>
<ide> stmt.free_result
<del> stmt.close if binds.empty?
<add> stmt.close if !cache_stmt
<ide>
<ide> [result_set, affected_rows]
<ide> end | 1 |
Ruby | Ruby | pass the mktemp prefix as an argument | b35d9906e5d9bdf580701b18304561ffbf36dcb8 | <ide><path>Library/Homebrew/extend/fileutils.rb
<ide> module FileUtils extend self
<ide>
<ide> # Create a temporary directory then yield. When the block returns,
<ide> # recursively delete the temporary directory.
<del> def mktemp
<del> # Prefer download_name if it is defined, for two reasons:
<del> # - The name attribute may be nil for resources that represent primary
<del> # formula downloads, in which case we want to use just the owner name.
<del> # - For resources that have a name defined, we want to use "owner--name"
<del> # instead of just "name"
<del> prefix = download_name if respond_to?(:download_name)
<del> prefix ||= name
<del>
<add> def mktemp(prefix=name)
<ide> # I used /tmp rather than `mktemp -td` because that generates a directory
<ide> # name with exotic characters like + in it, and these break badly written
<ide> # scripts that don't escape strings before trying to regexp them :(
<ide><path>Library/Homebrew/resource.rb
<ide> def cached_download
<ide> def stage(target=nil)
<ide> fetched = fetch
<ide> verify_download_integrity(fetched) if fetched.respond_to?(:file?) and fetched.file?
<del> mktemp do
<add> mktemp(download_name) do
<ide> downloader.stage
<ide> if block_given?
<ide> yield self | 2 |
Ruby | Ruby | rearrange logic to use positive branches | c75153d280e70e501c9044286ff52e50fe29a054 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def convert_hashes_to_parameters(key, value, assign_if_converted=true)
<ide> end
<ide>
<ide> def convert_value_to_parameters(value)
<del> if value.is_a?(Array) && !converted_arrays.member?(value)
<add> case value
<add> when Array
<add> return value if converted_arrays.member?(value)
<ide> converted = value.map { |_| convert_value_to_parameters(_) }
<ide> converted_arrays << converted
<ide> converted
<del> elsif value.is_a?(Parameters) || !value.is_a?(Hash)
<del> value
<del> else
<add> when Hash
<ide> self.class.new(value)
<add> else
<add> value
<ide> end
<ide> end
<ide> | 1 |
Go | Go | extract xattrs from tarfiles | c8428d77fdde41786aa5c0c4e64e0e762f873676 | <ide><path>archive/archive.go
<ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader) e
<ide> return err
<ide> }
<ide>
<add> for key, value := range hdr.Xattrs {
<add> if err := Lsetxattr(path, key, []byte(value), 0); err != nil {
<add> return err
<add> }
<add> }
<add>
<ide> // There is no LChmod, so ignore mode for symlink. Also, this
<ide> // must happen after chown, as that can modify the file mode
<ide> if hdr.Typeflag != tar.TypeSymlink { | 1 |
Ruby | Ruby | fix spelling of envelopeencryptionperformancetest | 33baf0dabd6ed70508104e172cb6c09976069c8e | <ide><path>activerecord/test/cases/encryption/performance/envelope_encryption_performance_test.rb
<ide> require "cases/encryption/helper"
<ide> require "models/book_encrypted"
<ide>
<del>class ActiveRecord::Encryption::EvenlopeEncryptionPerformanceTest < ActiveRecord::EncryptionTestCase
<add>class ActiveRecord::Encryption::EnvelopeEncryptionPerformanceTest < ActiveRecord::EncryptionTestCase
<ide> fixtures :encrypted_books
<ide>
<ide> setup do | 1 |
Text | Text | update translation breadth-first-search | 642e1275f4874b2f6bc87250c7a0966e754fc607 | <ide><path>guide/portuguese/algorithms/graph-algorithms/breadth-first-search/index.md
<ide> localeTitle: Largura da Primeira Pesquisa (BFS)
<ide> ---
<ide> ## Largura da Primeira Pesquisa (BFS)
<ide>
<del>Largura A primeira pesquisa é um dos algoritmos gráficos mais simples. Ele percorre o gráfico verificando primeiro o nó atual e expandindo-o adicionando seus sucessores ao próximo nível. O processo é repetido para todos os nós no nível atual antes de passar para o próximo nível. Se a solução for encontrada, a pesquisa será interrompida.
<add>Largura da Primeira Pesquisa é um dos algoritmos gráficos mais simples. Ele percorre o gráfico verificando primeiro o nó atual e expandindo-o adicionando seus sucessores ao próximo nível. O processo é repetido para todos os nós no nível atual antes de passar para o próximo nível. Se a solução for encontrada, a pesquisa será interrompida.
<ide>
<ide> ### Visualização
<ide>
<ide> Complexidade do espaço: O (n)
<ide>
<ide> Pior complexidade do tempo de caso: O (n)
<ide>
<del>Largura A primeira pesquisa é concluída em um conjunto finito de nós e é ideal se o custo de mover de um nó para outro é constante.
<add>Largura da Primeira Pesquisa é concluída em um conjunto finito de nós e é ideal se o custo de mover de um nó para outro é constante.
<ide>
<ide> ### Código C ++ para implementação do BFS
<ide>
<ide> Largura A primeira pesquisa é concluída em um conjunto finito de nós e é ide
<ide>
<ide> [Gráficos](https://github.com/freecodecamp/guides/computer-science/data-structures/graphs/index.md)
<ide>
<del>[Primeira pesquisa de profundidade (DFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md)
<ide>\ No newline at end of file
<add>[Primeira pesquisa de profundidade (DFS)](https://github.com/freecodecamp/guides/tree/master/src/pages/algorithms/graph-algorithms/depth-first-search/index.md) | 1 |
Java | Java | fix checkstyle violation | 1d0fe1223d8bfa47cc5d5c9a88e9a963419e73fe | <ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilderTests.java
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.mockito.ArgumentMatchers.any;
<del>import static org.mockito.ArgumentMatchers.anyInt;
<ide> import static org.mockito.BDDMockito.given;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.verify; | 1 |
Go | Go | setup ipv4 and ipv6 iptables chain | 06308f4d37009fb09f79b7206d661449fe0a488a | <ide><path>libnetwork/drivers/bridge/setup_ip_tables.go
<ide> func (n *bridgeNetwork) setupIPTables(ipVersion iptables.IPVersion, maskedAddr *
<ide> return iptable.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)
<ide> })
<ide>
<del> n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
<add> if ipVersion == iptables.IPv4 {
<add> n.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())
<add> } else {
<add> n.portMapperV6.SetIptablesChain(natChain, n.getNetworkBridgeName())
<add> }
<ide> }
<ide>
<ide> d.Lock() | 1 |
PHP | PHP | use a boolean flag for loading default config | 7d224d7b23717ad507fbf3792e4f42416f57fdcd | <ide><path>src/Core/InstanceConfigTrait.php
<ide> trait InstanceConfigTrait {
<ide> */
<ide> protected $_config = [];
<ide>
<add>/**
<add> * Whether the config property has already been configured with defaults
<add> *
<add> * @var bool
<add> */
<add> protected $_configInitialized = false;
<add>
<ide> /**
<ide> * ### Usage
<ide> *
<ide> trait InstanceConfigTrait {
<ide> * @throws \Cake\Error\Exception When trying to set a key that is invalid
<ide> */
<ide> public function config($key = null, $value = null) {
<del> if ($this->_config === [] && $this->_defaultConfig) {
<add> if (!$this->_configInitialized) {
<ide> $this->_config = $this->_defaultConfig;
<add> $this->_configInitialized = true;
<ide> }
<ide>
<ide> if (is_array($key) || func_num_args() === 2) { | 1 |
Python | Python | add sew ctc models | e1dc5afd28698d597321ef725467089d0924681c | <ide><path>src/transformers/models/sew/configuration_sew.py
<ide> def __init__(
<ide> mask_time_length=10,
<ide> mask_feature_prob=0.0,
<ide> mask_feature_length=10,
<del> ctc_loss_reduction="sum",
<add> ctc_loss_reduction="mean",
<ide> ctc_zero_infinity=False,
<ide> use_weighted_layer_sum=False,
<ide> classifier_proj_size=256,
<ide><path>src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py
<ide> "final_layer_norm": "encoder.layers.*.final_layer_norm",
<ide> "encoder.upsample.0": "encoder.upsample.projection",
<ide> "encoder.layer_norm": "encoder.layer_norm",
<del> "w2v_encoder.layer_norm": "layer_norm",
<add> "w2v_model.layer_norm": "layer_norm",
<ide> "w2v_encoder.proj": "lm_head",
<ide> "mask_emb": "masked_spec_embed",
<ide> }
<ide> def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
<ide> for key, mapped_key in MAPPING.items():
<ide> mapped_key = "sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key
<ide>
<del> if key in name or key.split("w2v_encoder.")[-1] == name.split(".")[0]:
<add> if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
<ide> is_used = True
<ide> if "*" in mapped_key:
<ide> layer_index = name.split(key)[0].split(".")[-2]
<ide> def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_gro
<ide> unused_weights.append(full_name)
<ide>
<ide>
<del>def convert_config(model):
<add>def convert_config(model, is_finetuned):
<ide> config = SEWConfig()
<del> fs_config = model.cfg
<add> if is_finetuned:
<add> fs_config = model.w2v_encoder.w2v_model.cfg
<add> else:
<add> fs_config = model.cfg
<ide>
<del> config.activation_dropout = fs_config.activation_dropout
<del> config.apply_spec_augment = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
<del> config.attention_dropout = fs_config.attention_dropout
<ide> config.conv_bias = fs_config.conv_bias
<ide> conv_layers = eval(fs_config.conv_feature_layers)
<ide> config.conv_dim = [x[0] for x in conv_layers]
<ide> config.conv_kernel = [x[1] for x in conv_layers]
<ide> config.conv_stride = [x[2] for x in conv_layers]
<ide> config.feat_extract_activation = "gelu"
<ide> config.feat_extract_norm = "layer" if fs_config.extractor_mode == "layer_norm" else "group"
<del> config.feat_proj_dropout = fs_config.dropout_input
<ide> config.final_dropout = 0.0
<ide> config.hidden_act = fs_config.activation_fn.name
<del> config.hidden_dropout = fs_config.dropout
<ide> config.hidden_size = fs_config.encoder_embed_dim
<ide> config.initializer_range = 0.02
<ide> config.intermediate_size = fs_config.encoder_ffn_embed_dim
<ide> config.layer_norm_eps = 1e-5
<ide> config.layerdrop = fs_config.encoder_layerdrop
<del> config.mask_feature_length = fs_config.mask_channel_length
<del> config.mask_feature_prob = fs_config.mask_channel_prob
<del> config.mask_time_length = fs_config.mask_length
<del> config.mask_time_prob = fs_config.mask_prob
<ide> config.num_attention_heads = fs_config.encoder_attention_heads
<ide> config.num_conv_pos_embedding_groups = fs_config.conv_pos_groups
<ide> config.num_conv_pos_embeddings = fs_config.conv_pos
<ide> config.num_feat_extract_layers = len(conv_layers)
<ide> config.num_hidden_layers = fs_config.encoder_layers
<ide> config.squeeze_factor = fs_config.squeeze_factor
<ide>
<add> # take care of any params that are overridden by the Wav2VecCtc model
<add> if is_finetuned:
<add> fs_config = model.cfg
<add> config.final_dropout = fs_config.final_dropout
<add> config.layerdrop = fs_config.layerdrop
<add> config.activation_dropout = fs_config.activation_dropout
<add> config.apply_spec_augment = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
<add> config.attention_dropout = fs_config.attention_dropout
<add> config.feat_proj_dropout = fs_config.dropout_input
<add> config.hidden_dropout = fs_config.dropout
<add> config.mask_feature_length = fs_config.mask_channel_length
<add> config.mask_feature_prob = fs_config.mask_channel_prob
<add> config.mask_time_length = fs_config.mask_length
<add> config.mask_time_prob = fs_config.mask_prob
<add>
<add> config.feature_extractor_type = "Wav2Vec2FeatureExtractor"
<add> config.tokenizer_class = "Wav2Vec2CTCTokenizer"
<add>
<ide> return config
<ide>
<ide>
<ide> def convert_sew_checkpoint(
<ide> if config_path is not None:
<ide> config = SEWConfig.from_pretrained(config_path)
<ide> else:
<del> config = convert_config(model[0])
<add> config = convert_config(model[0], is_finetuned)
<ide> model = model[0].eval()
<ide>
<ide> return_attention_mask = True if config.feat_extract_norm == "layer" else False
<ide> def convert_sew_checkpoint(
<ide>
<ide> # important change bos & pad token id since CTC symbol is <pad> and
<ide> # not <s> as in fairseq
<add> target_dict.indices[target_dict.bos_word] = target_dict.pad_index
<add> target_dict.indices[target_dict.pad_word] = target_dict.bos_index
<ide> config.bos_token_id = target_dict.pad_index
<ide> config.pad_token_id = target_dict.bos_index
<ide> config.eos_token_id = target_dict.eos_index
<ide><path>src/transformers/models/sew/modeling_sew.py
<ide> from transformers.deepspeed import is_deepspeed_zero3_enabled
<ide>
<ide> from ...activations import ACT2FN
<del>from ...file_utils import (
<del> add_code_sample_docstrings,
<del> add_start_docstrings,
<del> add_start_docstrings_to_model_forward,
<del> replace_return_docstrings,
<del>)
<add>from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<ide> from ...modeling_utils import PreTrainedModel
<ide> from ...utils import logging
<ide> def __init__(self, config: SEWConfig):
<ide> self.feature_extractor = SEWFeatureExtractor(config)
<ide> self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
<ide>
<add> self.project_features = config.conv_dim[-1] != config.hidden_size
<add> if self.project_features:
<add> self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
<add> self.feature_dropout = nn.Dropout(config.feat_proj_dropout)
<add>
<ide> self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())
<ide>
<ide> self.encoder = SEWEncoder(config)
<ide> def _mask_hidden_states(
<ide> return hidden_states
<ide>
<ide> @add_start_docstrings_to_model_forward(SEW_INPUTS_DOCSTRING)
<del> @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
<add> @add_code_sample_docstrings(
<add> processor_class=_PROCESSOR_FOR_DOC,
<add> checkpoint=_CHECKPOINT_FOR_DOC,
<add> output_type=BaseModelOutput,
<add> config_class=_CONFIG_FOR_DOC,
<add> modality="audio",
<add> )
<ide> def forward(
<ide> self,
<ide> input_values,
<ide> def forward(
<ide> output_hidden_states=None,
<ide> return_dict=None,
<ide> ):
<del> """
<del>
<del> Returns:
<del>
<del> Example::
<del>
<del> >>> from transformers import Wav2Vec2Processor, SEWModel
<del> >>> from datasets import load_dataset
<del> >>> import soundfile as sf
<del>
<del> >>> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-tiny-100k")
<del> >>> model = SEWModel.from_pretrained("asapp/sew-tiny-100k")
<del>
<del> >>> def map_to_array(batch):
<del> ... speech, _ = sf.read(batch["file"])
<del> ... batch["speech"] = speech
<del> ... return batch
<del>
<del> >>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation")
<del> >>> ds = ds.map(map_to_array)
<del>
<del> >>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values # Batch size 1
<del> >>> hidden_states = model(input_values).last_hidden_state
<del> """
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> output_hidden_states = (
<ide> output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
<ide> def forward(
<ide> extract_features = extract_features.transpose(1, 2)
<ide> extract_features = self.layer_norm(extract_features)
<ide>
<add> if self.project_features:
<add> extract_features = self.feature_projection(extract_features)
<add> hidden_states = self.feature_dropout(extract_features)
<add>
<ide> if attention_mask is not None:
<ide> # compute reduced attention_mask corresponding to feature vectors
<del> attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
<add> attention_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
<ide>
<del> hidden_states = self._mask_hidden_states(extract_features, mask_time_indices=mask_time_indices)
<add> hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
<ide>
<ide> encoder_outputs = self.encoder(
<ide> hidden_states,
<ide><path>src/transformers/models/sew_d/configuration_sew_d.py
<ide> def __init__(
<ide> mask_time_length=10,
<ide> mask_feature_prob=0.0,
<ide> mask_feature_length=10,
<del> ctc_loss_reduction="sum",
<add> ctc_loss_reduction="mean",
<ide> ctc_zero_infinity=False,
<ide> use_weighted_layer_sum=False,
<ide> classifier_proj_size=256,
<ide><path>src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py
<ide> "encoder.encoder.LayerNorm": "encoder.encoder.LayerNorm",
<ide> "encoder.upsample.0": "encoder.upsample.projection",
<ide> "encoder.layer_norm": "encoder.layer_norm",
<del> "w2v_encoder.layer_norm": "layer_norm",
<add> "w2v_model.layer_norm": "layer_norm",
<ide> "w2v_encoder.proj": "lm_head",
<ide> "mask_emb": "masked_spec_embed",
<ide> }
<ide> def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
<ide> unused_weights = []
<ide> fairseq_dict = fairseq_model.state_dict()
<ide>
<del> feature_extractor = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor
<add> feature_extractor = hf_model.sew_d.feature_extractor if is_finetuned else hf_model.feature_extractor
<ide>
<ide> for name, value in fairseq_dict.items():
<ide> is_used = False
<ide> def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
<ide> for key, mapped_key in MAPPING.items():
<ide> mapped_key = "sew_d." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key
<ide>
<del> if key in name or key.split("w2v_encoder.")[-1] == name.split(".")[0]:
<add> if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
<ide> is_used = True
<ide> if "*" in mapped_key:
<ide> layer_index = name.split(key)[0].split(".")[-2]
<ide> def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_gro
<ide> unused_weights.append(full_name)
<ide>
<ide>
<del>def convert_config(model):
<add>def convert_config(model, is_finetuned):
<ide> config = SEWDConfig()
<del> fs_config = model.cfg
<add> if is_finetuned:
<add> fs_config = model.w2v_encoder.w2v_model.cfg
<add> else:
<add> fs_config = model.cfg
<ide>
<del> config.activation_dropout = fs_config.activation_dropout
<del> config.apply_spec_augment = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
<del> config.attention_dropout = fs_config.attention_dropout
<ide> config.conv_bias = fs_config.conv_bias
<ide> conv_layers = eval(fs_config.conv_feature_layers)
<ide> config.conv_dim = [x[0] for x in conv_layers]
<ide> config.conv_kernel = [x[1] for x in conv_layers]
<ide> config.conv_stride = [x[2] for x in conv_layers]
<ide> config.feat_extract_activation = "gelu"
<ide> config.feat_extract_norm = "layer" if fs_config.extractor_mode == "layer_norm" else "group"
<del> config.feat_proj_dropout = fs_config.dropout_input
<ide> config.final_dropout = 0.0
<ide> config.hidden_act = fs_config.activation_fn.name
<del> config.hidden_dropout = fs_config.dropout
<ide> config.hidden_size = fs_config.encoder_embed_dim
<ide> config.initializer_range = 0.02
<ide> config.intermediate_size = fs_config.encoder_ffn_embed_dim
<ide> config.layer_norm_eps = 1e-5
<ide> config.layerdrop = fs_config.encoder_layerdrop
<del> config.mask_feature_length = fs_config.mask_channel_length
<del> config.mask_feature_prob = fs_config.mask_channel_prob
<del> config.mask_time_length = fs_config.mask_length
<del> config.mask_time_prob = fs_config.mask_prob
<ide> config.num_attention_heads = fs_config.encoder_attention_heads
<ide> config.num_conv_pos_embedding_groups = fs_config.conv_pos_groups
<ide> config.num_conv_pos_embeddings = fs_config.conv_pos
<ide> def convert_config(model):
<ide> config.pos_att_type = tuple(fs_config.pos_att_type.split("|"))
<ide> config.norm_rel_ebd = fs_config.norm_rel_ebd
<ide>
<add> # take care of any params that are overridden by the Wav2VecCtc model
<add> if is_finetuned:
<add> fs_config = model.cfg
<add> config.final_dropout = fs_config.final_dropout
<add> config.layerdrop = fs_config.layerdrop
<add> config.activation_dropout = fs_config.activation_dropout
<add> config.apply_spec_augment = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
<add> config.attention_dropout = fs_config.attention_dropout
<add> config.feat_proj_dropout = fs_config.dropout_input
<add> config.hidden_dropout = fs_config.dropout
<add> config.mask_feature_length = fs_config.mask_channel_length
<add> config.mask_feature_prob = fs_config.mask_channel_prob
<add> config.mask_time_length = fs_config.mask_length
<add> config.mask_time_prob = fs_config.mask_prob
<add>
<add> config.feature_extractor_type = "Wav2Vec2FeatureExtractor"
<add> config.tokenizer_class = "Wav2Vec2CTCTokenizer"
<add>
<ide> return config
<ide>
<ide>
<ide> def convert_sew_checkpoint(
<ide> if config_path is not None:
<ide> config = SEWDConfig.from_pretrained(config_path)
<ide> else:
<del> config = convert_config(model[0])
<add> config = convert_config(model[0], is_finetuned)
<ide> model = model[0].eval()
<ide>
<ide> return_attention_mask = True if config.feat_extract_norm == "layer" else False
<ide> def convert_sew_checkpoint(
<ide>
<ide> # important change bos & pad token id since CTC symbol is <pad> and
<ide> # not <s> as in fairseq
<add> target_dict.indices[target_dict.bos_word] = target_dict.pad_index
<add> target_dict.indices[target_dict.pad_word] = target_dict.bos_index
<ide> config.bos_token_id = target_dict.pad_index
<ide> config.pad_token_id = target_dict.bos_index
<ide> config.eos_token_id = target_dict.eos_index
<ide><path>src/transformers/models/sew_d/modeling_sew_d.py
<ide> from transformers.deepspeed import is_deepspeed_zero3_enabled
<ide>
<ide> from ...activations import ACT2FN
<del>from ...file_utils import (
<del> add_code_sample_docstrings,
<del> add_start_docstrings,
<del> add_start_docstrings_to_model_forward,
<del> replace_return_docstrings,
<del>)
<add>from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
<ide> from ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput
<ide> from ...modeling_utils import PreTrainedModel
<ide> from ...utils import logging
<ide> def _get_feature_vector_attention_mask(self, feature_vector_length: int, attenti
<ide> "The bare SEW-D Model transformer outputting raw hidden-states without any specific head on top.",
<ide> SEWD_START_DOCSTRING,
<ide> )
<add># Copied from transformers.models.sew.modeling_sew.SEWModel with SEW->SEWD
<ide> class SEWDModel(SEWDPreTrainedModel):
<ide> def __init__(self, config: SEWDConfig):
<ide> super().__init__(config)
<ide> self.config = config
<ide> self.feature_extractor = SEWDFeatureExtractor(config)
<ide> self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
<del> self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
<add>
<add> self.project_features = config.conv_dim[-1] != config.hidden_size
<add> if self.project_features:
<add> self.feature_projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
<ide> self.feature_dropout = nn.Dropout(config.feat_proj_dropout)
<ide>
<ide> self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())
<ide> def _mask_hidden_states(
<ide> return hidden_states
<ide>
<ide> @add_start_docstrings_to_model_forward(SEWD_INPUTS_DOCSTRING)
<del> @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
<add> @add_code_sample_docstrings(
<add> processor_class=_PROCESSOR_FOR_DOC,
<add> checkpoint=_CHECKPOINT_FOR_DOC,
<add> output_type=BaseModelOutput,
<add> config_class=_CONFIG_FOR_DOC,
<add> modality="audio",
<add> )
<ide> def forward(
<ide> self,
<ide> input_values,
<ide> def forward(
<ide> output_hidden_states=None,
<ide> return_dict=None,
<ide> ):
<del> """
<del>
<del> Returns:
<del>
<del> Example::
<del>
<del> >>> from transformers import Wav2Vec2Processor, SEWDModel
<del> >>> from datasets import load_dataset
<del> >>> import soundfile as sf
<del>
<del> >>> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-tiny-100k")
<del> >>> model = SEWDModel.from_pretrained("asapp/sew-tiny-100k")
<del>
<del> >>> def map_to_array(batch):
<del> ... speech, _ = sf.read(batch["file"])
<del> ... batch["speech"] = speech
<del> ... return batch
<del>
<del> >>> ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation")
<del> >>> ds = ds.map(map_to_array)
<del>
<del> >>> input_values = processor(ds["speech"][0], return_tensors="pt").input_values # Batch size 1
<del> >>> hidden_states = model(input_values).last_hidden_state
<del> """
<ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
<ide> output_hidden_states = (
<ide> output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
<ide> def forward(
<ide> extract_features = extract_features.transpose(1, 2)
<ide> extract_features = self.layer_norm(extract_features)
<ide>
<add> if self.project_features:
<add> extract_features = self.feature_projection(extract_features)
<add> hidden_states = self.feature_dropout(extract_features)
<add>
<ide> if attention_mask is not None:
<ide> # compute reduced attention_mask corresponding to feature vectors
<del> attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
<del>
<del> hidden_states = self.feature_projection(extract_features)
<del> hidden_states = self.feature_dropout(hidden_states)
<add> attention_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
<ide>
<ide> hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)
<ide>
<ide><path>tests/test_modeling_sew.py
<ide>
<ide> from tests.test_modeling_common import floats_tensor, ids_tensor, random_attention_mask
<ide> from transformers import SEWConfig, is_torch_available
<del>from transformers.testing_utils import require_datasets, require_soundfile, require_torch, slow, tooslow, torch_device
<add>from transformers.testing_utils import require_datasets, require_soundfile, require_torch, slow, torch_device
<ide>
<ide> from .test_configuration_common import ConfigTester
<ide> from .test_modeling_common import ModelTesterMixin, _config_zero_init
<ide> def test_inference_pretrained_batched(self):
<ide> self.assertTrue(torch.allclose(outputs[:, -4:, -4:], expected_outputs_last, atol=5e-3))
<ide> self.assertTrue(abs(outputs.sum() - expected_output_sum) < 5)
<ide>
<del> @tooslow
<ide> def test_inference_ctc_batched(self):
<del> # TODO: enable this test once the finetuned models are available
<del> model = SEWForCTC.from_pretrained("asapp/sew-tiny-100k-ft-100h").to(torch_device)
<del> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-tiny-100k-ft-100h", do_lower_case=True)
<add> model = SEWForCTC.from_pretrained("asapp/sew-tiny-100k-ft-ls100h").to(torch_device)
<add> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-tiny-100k-ft-ls100h", do_lower_case=True)
<ide>
<ide> input_speech = self._load_datasamples(2)
<ide>
<ide> inputs = processor(input_speech, return_tensors="pt", padding=True)
<ide>
<ide> input_values = inputs.input_values.to(torch_device)
<del> attention_mask = inputs.attention_mask.to(torch_device)
<ide>
<ide> with torch.no_grad():
<del> logits = model(input_values, attention_mask=attention_mask).logits
<add> logits = model(input_values).logits
<ide>
<ide> predicted_ids = torch.argmax(logits, dim=-1)
<ide> predicted_trans = processor.batch_decode(predicted_ids)
<ide>
<ide> EXPECTED_TRANSCRIPTIONS = [
<ide> "a man said to the universe sir i exist",
<del> "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore",
<add> "swet covered brian's body trickling into the tightloine closs hat was the only garment he wore",
<ide> ]
<ide> self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS)
<ide><path>tests/test_modeling_sew_d.py
<ide>
<ide> from tests.test_modeling_common import floats_tensor, ids_tensor, random_attention_mask
<ide> from transformers import SEWDConfig, is_torch_available
<del>from transformers.testing_utils import require_datasets, require_soundfile, require_torch, slow, tooslow, torch_device
<add>from transformers.testing_utils import require_datasets, require_soundfile, require_torch, slow, torch_device
<ide>
<ide> from .test_configuration_common import ConfigTester
<ide> from .test_modeling_common import ModelTesterMixin, _config_zero_init
<ide> def test_inference_pretrained_batched(self):
<ide> self.assertTrue(torch.allclose(outputs[:, -4:, -4:], expected_outputs_last, atol=5e-3))
<ide> self.assertTrue(abs(outputs.sum() - expected_output_sum) < 5)
<ide>
<del> @tooslow
<ide> def test_inference_ctc_batched(self):
<del> # TODO: enable this test once the finetuned models are available
<del> model = SEWDForCTC.from_pretrained("asapp/sew-d-tiny-100k-ft-100h").to(torch_device)
<del> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-d-tiny-100k-ft-100h", do_lower_case=True)
<add> model = SEWDForCTC.from_pretrained("asapp/sew-d-tiny-100k-ft-ls100h").to(torch_device)
<add> processor = Wav2Vec2Processor.from_pretrained("asapp/sew-d-tiny-100k-ft-ls100h", do_lower_case=True)
<ide>
<ide> input_speech = self._load_datasamples(2)
<ide>
<ide> inputs = processor(input_speech, return_tensors="pt", padding=True)
<ide>
<ide> input_values = inputs.input_values.to(torch_device)
<del> attention_mask = inputs.attention_mask.to(torch_device)
<ide>
<ide> with torch.no_grad():
<del> logits = model(input_values, attention_mask=attention_mask).logits
<add> logits = model(input_values).logits
<ide>
<ide> predicted_ids = torch.argmax(logits, dim=-1)
<ide> predicted_trans = processor.batch_decode(predicted_ids)
<ide>
<ide> EXPECTED_TRANSCRIPTIONS = [
<ide> "a man said to the universe sir i exist",
<del> "sweat covered brion's body trickling into the tight loin cloth that was the only garment he wore",
<add> "swet covered breon's body trickling into the titlowing closs that was the only garmened he war",
<ide> ]
<ide> self.assertListEqual(predicted_trans, EXPECTED_TRANSCRIPTIONS) | 8 |
Javascript | Javascript | render footer correctly | 66c552390947434b3aab27f27ed9e8c1eaa26856 | <ide><path>client/utils/gatsby/layoutSelector.js
<ide> export default function layoutSelector({ element, props }) {
<ide> }
<ide>
<ide> const splitPath = pathname.split('/').filter(x => x);
<del> const isSuperBlock =
<del> (splitPath.length === 2 && splitPath[0]) === 'learn' ||
<del> (splitPath.length === 3 && splitPath[1]) === 'learn';
<ide>
<del> if (/\/learn\//.test(pathname) && !isSuperBlock) {
<add> const isChallenge =
<add> (splitPath.length === 4 && splitPath[0]) === 'learn' ||
<add> (splitPath.length === 5 && splitPath[1]) === 'learn';
<add>
<add> if (isChallenge) {
<ide> return (
<ide> <DefaultLayout pathname={pathname} showFooter={false}>
<ide> {element}
<ide><path>cypress/integration/learn/common-components/footer.js
<add>/* global cy */
<add>
<add>const selectors = {
<add> footer: '.site-footer'
<add>};
<add>
<add>describe('Footer', () => {
<add> it('Should render on landing page', () => {
<add> cy.visit('/');
<add> cy.get(selectors.footer).should('be.visible');
<add> });
<add>
<add> it('Should render on learn page', () => {
<add> cy.visit('/learn');
<add> cy.get(selectors.footer).should('be.visible');
<add> cy.visit('/learn/');
<add> cy.get(selectors.footer).should('be.visible');
<add> });
<add>
<add> it('Should render on superblock page', () => {
<add> cy.visit('/learn/responsive-web-design/');
<add> cy.get(selectors.footer).should('be.visible');
<add> });
<add>
<add> it('Should not render on challenge page', () => {
<add> cy.visit(
<add> '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements'
<add> );
<add> cy.get(selectors.footer).should('not.exist');
<add> });
<add>}); | 2 |
PHP | PHP | use jsonserialize in tojson | 5543406e19b7585964071a01c8f856b56200181b | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function setIncrementing($value)
<ide> */
<ide> public function toJson($options = 0)
<ide> {
<del> return json_encode($this->toArray(), $options);
<add> return json_encode($this->jsonSerialize(), $options);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | fix links and typos in fs.md | e2617a03888aed62965ebc208f13e1bb3e183aeb | <ide><path>doc/api/fs.md
<ide> changes:
<ide> parameter in case of success.
<ide> - version: v5.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/3163
<del> description: The `file` parameter can be a file descriptor now.
<add> description: The `path` parameter can be a file descriptor now.
<ide> -->
<ide>
<ide> * `path` {string|Buffer|URL|integer} filename or file descriptor
<ide> changes:
<ide> protocol. Support is currently still *experimental*.
<ide> - version: v5.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/3163
<del> description: The `file` parameter can be a file descriptor now.
<add> description: The `path` parameter can be a file descriptor now.
<ide> -->
<ide>
<ide> * `path` {string|Buffer|URL|integer} filename or file descriptor
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} default = `null`
<ide> * `flag` {string} default = `'r'`
<ide>
<del>Synchronous version of [`fs.readFile`][]. Returns the contents of the `file`.
<add>Synchronous version of [`fs.readFile()`][]. Returns the contents of the `path`.
<ide>
<ide> If the `encoding` option is specified then this function returns a
<ide> string. Otherwise it returns a buffer.
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> [`fs.mkdtemp()`]: #fs_fs_mkdtemp_prefix_options_callback
<ide> [`fs.open()`]: #fs_fs_open_path_flags_mode_callback
<ide> [`fs.read()`]: #fs_fs_read_fd_buffer_offset_length_position_callback
<del>[`fs.readFile`]: #fs_fs_readfile_file_options_callback
<add>[`fs.readFile()`]: #fs_fs_readfile_path_options_callback
<add>[`fs.readFileSync()`]: #fs_fs_readfilesync_path_options
<ide> [`fs.stat()`]: #fs_fs_stat_path_callback
<ide> [`fs.utimes()`]: #fs_fs_utimes_path_atime_mtime_callback
<ide> [`fs.watch()`]: #fs_fs_watch_filename_options_listener | 1 |
PHP | PHP | fix postgresql dump and load for windows | 12b4a9e3fefe28b0afe9f5dd590394b13e1efdce | <ide><path>src/Illuminate/Database/Schema/PostgresSchemaState.php
<ide> public function dump(Connection $connection, $path)
<ide> })->implode(' ');
<ide>
<ide> $this->makeProcess(
<del> $this->baseDumpCommand().' --file=$LARAVEL_LOAD_PATH '.$excludedTables
<add> $this->baseDumpCommand().' --file="${:LARAVEL_LOAD_PATH}" '.$excludedTables
<ide> )->mustRun($this->output, array_merge($this->baseVariables($this->connection->getConfig()), [
<ide> 'LARAVEL_LOAD_PATH' => $path,
<ide> ]));
<ide> public function dump(Connection $connection, $path)
<ide> */
<ide> public function load($path)
<ide> {
<del> $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_restore --no-owner --no-acl --clean --if-exists --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE $LARAVEL_LOAD_PATH';
<add> $command = 'pg_restore --no-owner --no-acl --clean --if-exists --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}" "${:LARAVEL_LOAD_PATH}"';
<ide>
<ide> if (Str::endsWith($path, '.sql')) {
<del> $command = 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD psql --file=$LARAVEL_LOAD_PATH --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER --dbname=$LARAVEL_LOAD_DATABASE';
<add> $command = 'psql --file="${:LARAVEL_LOAD_PATH}" --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"';
<ide> }
<ide>
<ide> $process = $this->makeProcess($command);
<ide> public function load($path)
<ide> */
<ide> protected function baseDumpCommand()
<ide> {
<del> return 'PGPASSWORD=$LARAVEL_LOAD_PASSWORD pg_dump --no-owner --no-acl -Fc --host=$LARAVEL_LOAD_HOST --port=$LARAVEL_LOAD_PORT --username=$LARAVEL_LOAD_USER $LARAVEL_LOAD_DATABASE';
<add> return 'pg_dump --no-owner --no-acl -Fc --host="${:LARAVEL_LOAD_HOST}" --port="${:LARAVEL_LOAD_PORT}" --username="${:LARAVEL_LOAD_USER}" --dbname="${:LARAVEL_LOAD_DATABASE}"';
<ide> }
<ide>
<ide> /**
<ide> protected function baseVariables(array $config)
<ide> 'LARAVEL_LOAD_HOST' => is_array($config['host']) ? $config['host'][0] : $config['host'],
<ide> 'LARAVEL_LOAD_PORT' => $config['port'],
<ide> 'LARAVEL_LOAD_USER' => $config['username'],
<del> 'LARAVEL_LOAD_PASSWORD' => $config['password'],
<add> 'PGPASSWORD' => $config['password'],
<ide> 'LARAVEL_LOAD_DATABASE' => $config['database'],
<ide> ];
<ide> } | 1 |
Go | Go | add james golick to names generator | bf66deeb080787c3bda9aa619d3cdb22c68bbee1 | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> // Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine
<ide> "goldstine",
<ide>
<add> // James Golick, all around gangster.
<add> "golick",
<add>
<ide> // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall
<ide> "goodall",
<ide> | 1 |
Java | Java | fix circular placeholder prevention | 18006c72b014246946fd487159de7e133d173a17 | <ide><path>spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 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> protected String parseStringValue(
<ide> int endIndex = findPlaceholderEndIndex(buf, startIndex);
<ide> if (endIndex != -1) {
<ide> String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
<del> if (!visitedPlaceholders.add(placeholder)) {
<add> String originalPlaceholder = placeholder;
<add> if (!visitedPlaceholders.add(originalPlaceholder)) {
<ide> throw new IllegalArgumentException(
<del> "Circular placeholder reference '" + placeholder + "' in property definitions");
<add> "Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
<ide> }
<ide> // Recursive invocation, parsing placeholders contained in the placeholder key.
<ide> placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
<ide> else if (this.ignoreUnresolvablePlaceholders) {
<ide> throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'");
<ide> }
<ide>
<del> visitedPlaceholders.remove(placeholder);
<add> visitedPlaceholders.remove(originalPlaceholder);
<ide> }
<ide> else {
<ide> startIndex = -1;
<ide><path>spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void testRecurseInPlaceholder() {
<ide> props.setProperty("inner", "ar");
<ide>
<ide> assertEquals("foo=bar", this.helper.replacePlaceholders(text, props));
<add>
<add> text = "${top}";
<add> props = new Properties();
<add> props.setProperty("top", "${child}+${child}");
<add> props.setProperty("child", "${${differentiator}.grandchild}");
<add> props.setProperty("differentiator", "first");
<add> props.setProperty("first.grandchild", "actualValue");
<add>
<add> assertEquals("actualValue+actualValue", this.helper.replacePlaceholders(text, props));
<ide> }
<ide>
<ide> @Test | 2 |
Java | Java | restore use of spmcarrayqueue in rxringbuffer | 58a9d34ec36d6f836e85e551ac495cd33895a704 | <ide><path>rxjava-core/src/main/java/rx/internal/util/RxRingBuffer.java
<ide> import rx.Subscription;
<ide> import rx.exceptions.MissingBackpressureException;
<ide> import rx.internal.operators.NotificationLite;
<add>import rx.internal.util.unsafe.SpmcArrayQueue;
<add>import rx.internal.util.unsafe.SpscArrayQueue;
<ide> import rx.internal.util.unsafe.UnsafeAccess;
<ide>
<ide> /**
<ide> public class RxRingBuffer implements Subscription {
<ide>
<ide> public static RxRingBuffer getSpscInstance() {
<ide> if (UnsafeAccess.isUnsafeAvailable()) {
<del> // using SynchronizedQueue until issues are solved with SpscArrayQueue offer rejection
<del> // RxRingBufferSpmcTest.testConcurrency occasionally fails with a
<del> // BackpressureException when using SpscArrayQueue
<del> // return new RxRingBuffer(SPSC_POOL, SIZE); // this is the one we were trying to use
<del> // return new RxRingBuffer(new SpscArrayQueue<Object>(SIZE), SIZE);
<del> // the performance of this is sufficient (actually faster in some cases)
<del> return new RxRingBuffer(new SynchronizedQueue<Object>(SIZE), SIZE);
<add> // TODO the SpscArrayQueue isn't ready yet so using SpmcArrayQueue for now
<add> return new RxRingBuffer(SPMC_POOL, SIZE);
<ide> } else {
<ide> return new RxRingBuffer();
<ide> }
<ide> }
<ide>
<ide> public static RxRingBuffer getSpmcInstance() {
<ide> if (UnsafeAccess.isUnsafeAvailable()) {
<del> // using SynchronizedQueue until issues are solved with SpmcArrayQueue offer rejection
<del> // RxRingBufferSpmcTest.testConcurrency occasionally fails with a
<del> // BackpressureException when using SpmcArrayQueue/MpmcArrayQueue
<del> // return new RxRingBuffer(SPMC_POOL, SIZE); // this is the one we were trying to use
<del> // return new RxRingBuffer(new SpmcArrayQueue<Object>(SIZE), SIZE);
<del> // return new RxRingBuffer(new MpmcArrayQueue<Object>(SIZE), SIZE);
<del> // the performance of this is sufficient (actually faster in some cases)
<del> return new RxRingBuffer(new SynchronizedQueue<Object>(SIZE), SIZE);
<add> return new RxRingBuffer(SPMC_POOL, SIZE);
<ide> } else {
<ide> return new RxRingBuffer();
<ide> }
<ide> public static RxRingBuffer getSpmcInstance() {
<ide>
<ide> public static final int SIZE = 1024;
<ide>
<add> private static ObjectPool<Queue<Object>> SPSC_POOL = new ObjectPool<Queue<Object>>() {
<add>
<add> @Override
<add> protected SpscArrayQueue<Object> createObject() {
<add> return new SpscArrayQueue<Object>(SIZE);
<add> }
<add>
<add> };
<add>
<add> private static ObjectPool<Queue<Object>> SPMC_POOL = new ObjectPool<Queue<Object>>() {
<add>
<add> @Override
<add> protected SpmcArrayQueue<Object> createObject() {
<add> return new SpmcArrayQueue<Object>(SIZE);
<add> }
<add>
<add> };
<add>
<ide> private RxRingBuffer(Queue<Object> queue, int size) {
<ide> this.queue = queue;
<ide> this.pool = null;
<ide><path>rxjava-core/src/main/java/rx/internal/util/unsafe/SpmcArrayQueue.java
<ide> public boolean offer(final E e) {
<ide> final long currProducerIndex = lvProducerIndex();
<ide> final long offset = calcElementOffset(currProducerIndex);
<ide> if (null != lvElement(lb, offset)) {
<del> return false;
<add> // strict check as per https://github.com/JCTools/JCTools/issues/21#issuecomment-50204120
<add> int size = (int) (currProducerIndex - lvConsumerIndex());
<add> if (size == capacity) {
<add> return false;
<add> }
<add> else {
<add> // spin wait for slot to clear, buggers wait freedom
<add> while (null != lvElement(lb, offset));
<add> }
<ide> }
<ide> spElement(lb, offset, e);
<ide> // single producer, so store ordered is valid. It is also required to correctly publish the element | 2 |
Go | Go | add additional unit-tests | c815b86f407a7566675ce5a737730ae5754b53e5 | <ide><path>profiles/seccomp/seccomp_test.go
<ide> func TestLoadProfileWithListenerPath(t *testing.T) {
<ide> assert.DeepEqual(t, expected, *p)
<ide> }
<ide>
<add>// TestLoadProfileValidation tests that invalid profiles produce the correct error.
<add>func TestLoadProfileValidation(t *testing.T) {
<add> tests := []struct {
<add> doc string
<add> profile string
<add> expected string
<add> }{
<add> {
<add> doc: "conflicting architectures and archMap",
<add> profile: `{"defaultAction": "SCMP_ACT_ERRNO", "architectures": ["A", "B", "C"], "archMap": [{"architecture": "A", "subArchitectures": ["B", "C"]}]}`,
<add> expected: `use either 'architectures' or 'archMap'`,
<add> },
<add> {
<add> doc: "conflicting syscall.name and syscall.names",
<add> profile: `{"defaultAction": "SCMP_ACT_ERRNO", "syscalls": [{"name": "accept", "names": ["accept"], "action": "SCMP_ACT_ALLOW"}]}`,
<add> expected: `use either 'name' or 'names'`,
<add> },
<add> }
<add> for _, tc := range tests {
<add> tc := tc
<add> rs := createSpec()
<add> t.Run(tc.doc, func(t *testing.T) {
<add> _, err := LoadProfile(tc.profile, &rs)
<add> assert.ErrorContains(t, err, tc.expected)
<add> })
<add> }
<add>}
<add>
<ide> // TestLoadLegacyProfile tests loading a seccomp profile in the old format
<ide> // (before https://github.com/docker/docker/pull/24510)
<ide> func TestLoadLegacyProfile(t *testing.T) {
<ide> func TestLoadLegacyProfile(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> rs := createSpec()
<del> if _, err := LoadProfile(string(f), &rs); err != nil {
<del> t.Fatal(err)
<add> p, err := LoadProfile(string(f), &rs)
<add> assert.NilError(t, err)
<add> assert.Equal(t, p.DefaultAction, specs.ActErrno)
<add> assert.DeepEqual(t, p.Architectures, []specs.Arch{"SCMP_ARCH_X86_64", "SCMP_ARCH_X86", "SCMP_ARCH_X32"})
<add> assert.Equal(t, len(p.Syscalls), 311)
<add> expected := specs.LinuxSyscall{
<add> Names: []string{"accept"},
<add> Action: specs.ActAllow,
<add> Args: []specs.LinuxSeccompArg{},
<ide> }
<add> assert.DeepEqual(t, p.Syscalls[0], expected)
<ide> }
<ide>
<ide> func TestLoadDefaultProfile(t *testing.T) { | 1 |
Javascript | Javascript | remove unused ontimeout, add timeout tests | 33760ccc18e4be10cce3d39f59d374881c49ee2e | <ide><path>lib/internal/http2/core.js
<ide> const setTimeout = {
<ide> return this;
<ide> }
<ide> };
<del>
<del>const onTimeout = {
<del> configurable: false,
<del> enumerable: false,
<del> value: function() {
<del> process.nextTick(emit.bind(this, 'timeout'));
<del> }
<del>};
<del>
<del>Object.defineProperties(Http2Stream.prototype, {
<del> setTimeout,
<del> onTimeout
<del>});
<del>Object.defineProperties(Http2Session.prototype, {
<del> setTimeout,
<del> onTimeout
<del>});
<add>Object.defineProperty(Http2Stream.prototype, 'setTimeout', setTimeout);
<add>Object.defineProperty(Http2Session.prototype, 'setTimeout', setTimeout);
<ide>
<ide> // --------------------------------------------------------------------
<ide>
<ide><path>test/parallel/test-http2-server-startup.js
<ide> assert.doesNotThrow(() => {
<ide> if (client)
<ide> client.end();
<ide> }));
<del> server.setTimeout(common.platformTimeout(1000));
<add> server.setTimeout(common.platformTimeout(1000), common.mustCall());
<ide> server.listen(0, common.mustCall(() => {
<ide> const port = server.address().port;
<ide> client = net.connect(port, common.mustCall());
<ide> assert.doesNotThrow(() => {
<ide> if (client)
<ide> client.end();
<ide> }));
<del> server.setTimeout(common.platformTimeout(1000));
<add> server.setTimeout(common.platformTimeout(1000), common.mustCall());
<ide> server.listen(0, common.mustCall(() => {
<ide> const port = server.address().port;
<ide> client = tls.connect({
<ide><path>test/parallel/test-http2-timeouts.js
<ide> server.on('stream', common.mustCall((stream) => {
<ide> stream.respond({ ':status': 200 });
<ide> stream.end('hello world');
<ide> }));
<add>
<add> // check that expected errors are thrown with wrong args
<add> common.expectsError(
<add> () => stream.setTimeout('100'),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "msecs" argument must be of type number'
<add> }
<add> );
<add> common.expectsError(
<add> () => stream.setTimeout(0, Symbol('test')),
<add> {
<add> code: 'ERR_INVALID_CALLBACK',
<add> type: TypeError,
<add> message: 'Callback must be a function'
<add> }
<add> );
<add> common.expectsError(
<add> () => stream.setTimeout(100, {}),
<add> {
<add> code: 'ERR_INVALID_CALLBACK',
<add> type: TypeError,
<add> message: 'Callback must be a function'
<add> }
<add> );
<ide> }));
<ide> server.listen(0);
<ide> | 3 |
Java | Java | ignore client proxies for export | 59d9f73f46c147856479f17faef65317ce6eacea | <ide><path>org.springframework.web/src/main/java/org/springframework/remoting/jaxws/AbstractJaxWsServiceExporter.java
<ide> public void publishEndpoints() {
<ide> for (String beanName : beanNames) {
<ide> try {
<ide> Class<?> type = this.beanFactory.getType(beanName);
<del> WebService wsAnnotation = type.getAnnotation(WebService.class);
<del> WebServiceProvider wsProviderAnnotation = type.getAnnotation(WebServiceProvider.class);
<del> if (wsAnnotation != null || wsProviderAnnotation != null) {
<del> Endpoint endpoint = Endpoint.create(this.beanFactory.getBean(beanName));
<del> if (this.endpointProperties != null) {
<del> endpoint.setProperties(this.endpointProperties);
<add> if (type != null && !type.isInterface()) {
<add> WebService wsAnnotation = type.getAnnotation(WebService.class);
<add> WebServiceProvider wsProviderAnnotation = type.getAnnotation(WebServiceProvider.class);
<add> if (wsAnnotation != null || wsProviderAnnotation != null) {
<add> Endpoint endpoint = Endpoint.create(this.beanFactory.getBean(beanName));
<add> if (this.endpointProperties != null) {
<add> endpoint.setProperties(this.endpointProperties);
<add> }
<add> if (this.executor != null) {
<add> endpoint.setExecutor(this.executor);
<add> }
<add> if (wsAnnotation != null) {
<add> publishEndpoint(endpoint, wsAnnotation);
<add> }
<add> else {
<add> publishEndpoint(endpoint, wsProviderAnnotation);
<add> }
<add> this.publishedEndpoints.add(endpoint);
<ide> }
<del> if (this.executor != null) {
<del> endpoint.setExecutor(this.executor);
<del> }
<del> if (wsAnnotation != null) {
<del> publishEndpoint(endpoint, wsAnnotation);
<del> }
<del> else {
<del> publishEndpoint(endpoint, wsProviderAnnotation);
<del> }
<del> this.publishedEndpoints.add(endpoint);
<ide> }
<ide> }
<ide> catch (CannotLoadBeanClassException ex) { | 1 |
PHP | PHP | fix incomplete patch 61dd1098d3 | 56a0eb04b799bd01b8c9d32698fef1725785ee7f | <ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php
<ide> public function testNumbers() {
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<add> $result = $this->Paginator->numbers(array('modulus' => 3, 'currentTag' => 'span', 'tag' => 'li'));
<add> $expected = array(
<add> array('li' => array('class' => 'current')), array('span' => array()), '1', '/span', '/li',
<add> ' | ',
<add> array('li' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/li',
<add> ' | ',
<add> array('li' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/li',
<add> );
<add> $this->assertTags($result, $expected);
<add>
<ide> $this->Paginator->request->params['paging'] = array(
<ide> 'Client' => array(
<ide> 'page' => 2,
<ide><path>lib/Cake/View/Helper/PaginatorHelper.php
<ide> public function numbers($options = array()) {
<ide> if ($class) {
<ide> $currentClass .= ' ' . $class;
<ide> }
<del> $out .= $this->Html->tag($tag, $i, array('class' => $currentClass));
<add> if ($currentTag) {
<add> $out .= $this->Html->tag($tag, $this->Html->tag($currentTag, $i), array('class' => $currentClass));
<add> } else {
<add> $out .= $this->Html->tag($tag, $i, array('class' => $currentClass));
<add> }
<ide> } else {
<ide> $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class'));
<ide> } | 2 |
Javascript | Javascript | remove dynamic gks for selective/train | cf7a0c24d4640f07d465c5a67aab2639ddd5d0a9 | <ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide>
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<ide>
<del>export const enableTrainModelFix = __EXPERIMENTAL__;
<add>export const enableTrainModelFix = true;
<ide>
<ide> export const enableTrustedTypesIntegration = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const warnAboutStringRefs = false;
<ide> export const disableLegacyContext = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enableTrainModelFix = false;
<add>export const enableTrainModelFix = true;
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const disableCreateFactory = false;
<ide> export const disableTextareaChildren = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const warnAboutStringRefs = false;
<ide> export const disableLegacyContext = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enableTrainModelFix = false;
<add>export const enableTrainModelFix = true;
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const enableNativeTargetAsInstance = false;
<ide> export const disableCreateFactory = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.persistent.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const warnAboutStringRefs = false;
<ide> export const disableLegacyContext = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enableTrainModelFix = false;
<add>export const enableTrainModelFix = true;
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const enableNativeTargetAsInstance = false;
<ide> export const disableCreateFactory = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const warnAboutStringRefs = false;
<ide> export const disableLegacyContext = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enableTrainModelFix = false;
<add>export const enableTrainModelFix = true;
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const enableNativeTargetAsInstance = false;
<ide> export const disableCreateFactory = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const warnAboutStringRefs = false;
<ide> export const disableLegacyContext = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<del>export const enableTrainModelFix = false;
<add>export const enableTrainModelFix = true;
<ide> export const enableTrustedTypesIntegration = false;
<ide> export const enableNativeTargetAsInstance = false;
<ide> export const disableCreateFactory = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> debugRenderPhaseSideEffectsForStrictMode,
<ide> disableInputAttributeSyncing,
<ide> enableTrustedTypesIntegration,
<del> enableSelectiveHydration,
<del> enableTrainModelFix,
<ide> } = require('ReactFeatureFlags');
<ide>
<ide> // In www, we have experimental support for gathering data
<ide> export const warnAboutStringRefs = false;
<ide> export const warnAboutDefaultPropsOnFunctionComponents = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<ide>
<add>export const enableTrainModelFix = true;
<add>
<ide> export const exposeConcurrentModeAPIs = __EXPERIMENTAL__;
<ide>
<ide> export const enableSuspenseServerRenderer = true;
<add>export const enableSelectiveHydration = true;
<ide>
<ide> export const enableChunksAPI = __EXPERIMENTAL__;
<ide> | 7 |
Go | Go | reduce logging verbosity in allocator | c2064dc18d91a69fb0a0383a73d21c06748cb019 | <ide><path>libnetwork/ipam/allocator.go
<ide> func (a *Allocator) parsePoolRequest(addressSpace, pool, subPool string, v6 bool
<ide> }
<ide>
<ide> func (a *Allocator) insertBitMask(key SubnetKey, pool *net.IPNet) error {
<del> log.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String())
<add> //log.Debugf("Inserting bitmask (%s, %s)", key.String(), pool.String())
<ide>
<ide> store := a.getStore(key.AddressSpace)
<ide> if store == nil {
<ide><path>libnetwork/sandbox_store.go
<ide> func (c *controller) sandboxCleanup() {
<ide> for _, kvo := range kvol {
<ide> sbs := kvo.(*sbState)
<ide>
<del> logrus.Printf("sandboxcleanup sbs = %+v", sbs)
<ide> sb := &sandbox{
<ide> id: sbs.ID,
<ide> controller: sbs.c, | 2 |
Text | Text | fix broken link in timers doc | 4e76bffc0c7076a5901179e70c7b8a8f9fcd22e4 | <ide><path>doc/api/timers.md
<ide> actions.
<ide> ## Class: Timeout
<ide>
<ide> This object is created internally and is returned from [`setTimeout()`][] and
<del>[`setInterval()`][]. It can be passed to [`clearTimeout`][] or
<add>[`setInterval()`][]. It can be passed to [`clearTimeout()`][] or
<ide> [`clearInterval()`][] (respectively) in order to cancel the scheduled actions.
<ide>
<ide> By default, when a timer is scheduled using either [`setTimeout()`][] or | 1 |
Javascript | Javascript | resolve preset es2015 from next directory (#949) | f9717347a48ce778db21a78a01083a177a9f9110 | <ide><path>server/build/webpack.js
<ide> export default async function createCompiler (dir, { dev = false, quiet = false
<ide> }
<ide>
<ide> const transpiled = babelCore.transform(content, {
<del> presets: ['es2015'],
<add> presets: [require.resolve('babel-preset-es2015')],
<ide> sourceMaps: dev ? 'both' : false,
<ide> inputSourceMap: sourceMap
<ide> }) | 1 |
PHP | PHP | fix regex for php 7.3 | e77eeb84488c1b0ef7fe7b1100b5f12aa8adaa0f | <ide><path>src/Database/SqlDialectTrait.php
<ide> public function quoteIdentifier($identifier)
<ide> }
<ide>
<ide> // Alias.field AS thing
<del> if (preg_match('/^([\w-]+(\.[\w-\s]+|\(.*\))*)\s+AS\s*([\w-]+)$/ui', $identifier, $matches)) {
<add> if (preg_match('/^([\w-]+(\.[\w\s-]+|\(.*\))*)\s+AS\s*([\w-]+)$/ui', $identifier, $matches)) {
<ide> return $this->quoteIdentifier($matches[1]) . ' AS ' . $this->quoteIdentifier($matches[3]);
<ide> }
<ide> | 1 |
Ruby | Ruby | bring am up to date with new rendering stack | 36eb1a686c831d5a14998bb9ac7cc60efa363373 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def collect_responses_and_parts_order(headers) #:nodoc:
<ide>
<ide> def each_template(paths, name, &block) #:nodoc:
<ide> Array(paths).each do |path|
<del> self.class.view_paths.each do |load_paths|
<del> templates = load_paths.find_all(name, {}, path)
<del> templates = templates.uniq_by { |t| t.details[:formats] }
<add> templates = lookup_context.find_all(name, path)
<ide>
<del> unless templates.empty?
<del> templates.each(&block)
<del> return
<del> end
<add> unless templates.empty?
<add> templates = templates.uniq_by { |t| t.details[:formats] }
<add> templates.each(&block)
<add> return
<ide> end
<ide> end
<ide> end
<ide><path>actionmailer/lib/action_mailer/old_api.rb
<ide> def create_parts
<ide> if String === @body
<ide> @parts.unshift create_inline_part(@body)
<ide> elsif @parts.empty? || @parts.all? { |p| p.content_disposition =~ /^attachment/ }
<del> self.class.view_paths.first.find_all(@template, {}, @mailer_name).each do |template|
<add> lookup_context.find_all(@template, @mailer_name).each do |template|
<ide> @parts << create_inline_part(render(:_template => template), template.mime_type)
<ide> end
<ide>
<ide><path>actionpack/lib/action_view/lookup_context.rb
<ide> def find_template(name, prefix = nil, partial = false)
<ide> @view_paths.find(name, key.details, prefix, partial || false, key)
<ide> end
<ide>
<add> def find_all(name, prefix = nil, partial = false)
<add> key = details_key
<add> @view_paths.find_all(name, key.details, prefix, partial || false, key)
<add> end
<add>
<ide> def template_exists?(name, prefix = nil, partial = false)
<ide> key = details_key
<ide> @view_paths.exists?(name, key.details, prefix, partial || false, key)
<ide><path>actionpack/lib/action_view/paths.rb
<ide> def #{method}(*args)
<ide> METHOD
<ide> end
<ide>
<add> def find_all(path, details = {}, prefix = nil, partial = false, key=nil)
<add> each do |resolver|
<add> templates = resolver.find_all(path, details, prefix, partial, key)
<add> return templates unless templates.empty?
<add> end
<add> []
<add> end
<add>
<ide> def find(path, details = {}, prefix = nil, partial = false, key=nil)
<ide> each do |resolver|
<ide> if template = resolver.find(path, details, prefix, partial, key)
<ide><path>actionpack/lib/action_view/render/rendering.rb
<ide> def _determine_template(options) #:nodoc:
<ide> Template::Text.new(options[:text], self.formats.try(:first))
<ide> elsif options.key?(:file)
<ide> with_fallbacks { find_template(options[:file], options[:_prefix]) }
<add> elsif options.key?(:_template)
<add> options[:_template]
<ide> elsif options.key?(:template)
<ide> find_template(options[:template], options[:_prefix])
<ide> end | 5 |
Ruby | Ruby | remove docs related to ruby 1.8 from array#wrap | 219342b642bb3e965147364fabe6a02a8edea559 | <ide><path>activesupport/lib/active_support/core_ext/array/wrap.rb
<ide> class Array
<ide> # Array(:foo => :bar) # => [[:foo, :bar]]
<ide> # Array.wrap(:foo => :bar) # => [{:foo => :bar}]
<ide> #
<del> # Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
<del> # Array.wrap("foo\nbar") # => ["foo\nbar"]
<del> #
<ide> # There's also a related idiom that uses the splat operator:
<ide> #
<ide> # [*object] | 1 |
Text | Text | add missing periods or colons | 392d80a617fab8630e3f017076f1f59403db6470 | <ide><path>doc/api/buffer.md
<ide> added: v3.0.0
<ide>
<ide> * {integer} The largest size allowed for a single `Buffer` instance.
<ide>
<del>An alias for [`buffer.constants.MAX_LENGTH`][]
<add>An alias for [`buffer.constants.MAX_LENGTH`][].
<ide>
<ide> Note that this is a property on the `buffer` module returned by
<ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance.
<ide><path>doc/api/child_process.md
<ide> child registers an event handler for the [`'disconnect'`][] event
<ide> or the [`'message'`][] event. This allows the child to exit
<ide> normally without the process being held open by the open IPC channel.*
<ide>
<del>See also: [`child_process.exec()`][] and [`child_process.fork()`][]
<add>See also: [`child_process.exec()`][] and [`child_process.fork()`][].
<ide>
<ide> ## Synchronous Process Creation
<ide>
<ide> process has exited.*
<ide>
<ide> If the process times out or has a non-zero exit code, this method ***will***
<ide> throw. The [`Error`][] object will contain the entire result from
<del>[`child_process.spawnSync()`][]
<add>[`child_process.spawnSync()`][].
<ide>
<ide> **Never pass unsanitized user input to this function. Any input containing shell
<ide> metacharacters may be used to trigger arbitrary command execution.**
<ide> does not indicate that the child process has been terminated.
<ide> added: v0.1.90
<ide> -->
<ide>
<del>* {number} Integer
<add>* {integer}
<ide>
<ide> Returns the process identifier (PID) of the child process.
<ide>
<ide><path>doc/api/cli.md
<ide> added: v6.0.0
<ide> -->
<ide>
<ide> Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with
<del>`./configure --openssl-fips`)
<add>`./configure --openssl-fips`.)
<ide>
<ide> ### `--experimental-modules`
<ide> <!-- YAML
<ide> added: v6.0.0
<ide> -->
<ide>
<ide> Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)
<del>(Same requirements as `--enable-fips`)
<add>(Same requirements as `--enable-fips`.)
<ide>
<ide> ### `--icu-data-dir=file`
<ide> <!-- YAML
<ide> added: v0.11.15
<ide> -->
<ide>
<del>Specify ICU data load path. (overrides `NODE_ICU_DATA`)
<add>Specify ICU data load path. (Overrides `NODE_ICU_DATA`.)
<ide>
<ide> ### `--inspect-brk[=[host:]port]`
<ide> <!-- YAML
<ide> Throw errors for deprecations.
<ide> added: v4.0.0
<ide> -->
<ide>
<del>Specify an alternative default TLS cipher list. (Requires Node.js to be built
<del>with crypto support. (Default))
<add>Specify an alternative default TLS cipher list. Requires Node.js to be built
<add>with crypto support (default).
<ide>
<ide> ### `--trace-deprecation`
<ide> <!-- YAML
<ide><path>doc/api/cluster.md
<ide> Each new worker is given its own unique id, this id is stored in the
<ide> `id`.
<ide>
<ide> While a worker is alive, this is the key that indexes it in
<del>cluster.workers
<add>`cluster.workers`.
<ide>
<ide> ### worker.isConnected()
<ide> <!-- YAML
<ide> All workers are created using [`child_process.fork()`][], the returned object
<ide> from this function is stored as `.process`. In a worker, the global `process`
<ide> is stored.
<ide>
<del>See: [Child Process module][]
<add>See: [Child Process module][].
<ide>
<ide> Note that workers will call `process.exit(0)` if the `'disconnect'` event occurs
<ide> on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
<ide> changes:
<ide> description: The `stdio` option is supported now.
<ide> -->
<ide>
<del>* `settings` {Object} see [`cluster.settings`][]
<add>* `settings` {Object} See [`cluster.settings`][].
<ide>
<ide> `setupMaster` is used to change the default 'fork' behavior. Once called,
<ide> the settings will be present in `cluster.settings`.
<ide><path>doc/api/console.md
<ide> changes:
<ide> Setting to `true` enables coloring while inspecting values, setting to
<ide> `'auto'` will make color support depend on the value of the `isTTY` property
<ide> and the value returned by `getColorDepth()` on the respective stream.
<del> **Default:** `'auto'`
<add> **Default:** `'auto'`.
<ide>
<ide> Creates a new `Console` with one or two writable stream instances. `stdout` is a
<ide> writable stream to print log or info output. `stderr` is used for warning or
<ide><path>doc/api/deprecations.md
<ide> explicitly via error event handlers set on the domain instead.
<ide> Type: End-of-Life
<ide>
<ide> Calling an asynchronous function without a callback throws a `TypeError`
<del>v10.0.0 onwards. Refer: [PR 12562](https://github.com/nodejs/node/pull/12562)
<add>v10.0.0 onwards. Refer: [PR 12562](https://github.com/nodejs/node/pull/12562).
<ide>
<ide> <a id="DEP0014"></a>
<ide> ### DEP0014: fs.read legacy String interface
<ide><path>doc/api/dgram.md
<ide> properties.
<ide> added: v0.1.99
<ide> -->
<ide>
<del>* `port` {number} Integer.
<add>* `port` {integer}
<ide> * `address` {string}
<ide> * `callback` {Function} with no parameters. Called when binding is complete.
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `msg` {Buffer|Uint8Array|string|Array} Message to be sent.
<del>* `offset` {number} Integer. Offset in the buffer where the message starts.
<del>* `length` {number} Integer. Number of bytes in the message.
<del>* `port` {number} Integer. Destination port.
<add>* `offset` {integer} Offset in the buffer where the message starts.
<add>* `length` {integer} Number of bytes in the message.
<add>* `port` {integer} Destination port.
<ide> * `address` {string} Destination hostname or IP address.
<ide> * `callback` {Function} Called when the message has been sent.
<ide>
<ide> multicast packets will also be received on the local interface.
<ide> added: v0.3.8
<ide> -->
<ide>
<del>* `ttl` {number} Integer.
<add>* `ttl` {integer}
<ide>
<ide> Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
<ide> "Time to Live", in this context it specifies the number of IP hops that a
<ide> between 0 and 255. The default on most systems is `1` but can vary.
<ide> added: v8.7.0
<ide> -->
<ide>
<del>* `size` {number} Integer
<add>* `size` {integer}
<ide>
<ide> Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
<ide> in bytes.
<ide> in bytes.
<ide> added: v8.7.0
<ide> -->
<ide>
<del>* `size` {number} Integer
<add>* `size` {integer}
<ide>
<ide> Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
<ide> in bytes.
<ide> in bytes.
<ide> added: v0.1.101
<ide> -->
<ide>
<del>* `ttl` {number} Integer.
<add>* `ttl` {integer}
<ide>
<ide> Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
<ide> in this context it specifies the number of IP hops that a packet is allowed to
<ide><path>doc/api/errors.md
<ide> entry types were found.
<ide> <a id="ERR_VALUE_OUT_OF_RANGE"></a>
<ide> ### ERR_VALUE_OUT_OF_RANGE
<ide>
<del>Superseded by `ERR_OUT_OF_RANGE`
<add>Superseded by `ERR_OUT_OF_RANGE`.
<ide>
<ide> <a id="ERR_VM_MODULE_ALREADY_LINKED"></a>
<ide> ### ERR_VM_MODULE_ALREADY_LINKED
<ide><path>doc/api/fs.md
<ide> added: v0.1.10
<ide>
<ide> Returns `true` if the `fs.Stats` object describes a symbolic link.
<ide>
<del>This method is only valid when using [`fs.lstat()`][]
<add>This method is only valid when using [`fs.lstat()`][].
<ide>
<ide> ### stats.dev
<ide>
<ide> changes:
<ide> Asynchronously changes the permissions of a file. No arguments other than a
<ide> possible exception are given to the completion callback.
<ide>
<del>See also: chmod(2)
<add>See also: chmod(2).
<ide>
<ide> ### File modes
<ide>
<ide> changes:
<ide> Synchronously changes the permissions of a file. Returns `undefined`.
<ide> This is the synchronous version of [`fs.chmod()`][].
<ide>
<del>See also: chmod(2)
<add>See also: chmod(2).
<ide>
<ide> ## fs.chown(path, uid, gid, callback)
<ide> <!-- YAML
<ide> changes:
<ide> Asynchronously changes owner and group of a file. No arguments other than a
<ide> possible exception are given to the completion callback.
<ide>
<del>See also: chown(2)
<add>See also: chown(2).
<ide>
<ide> ## fs.chownSync(path, uid, gid)
<ide> <!-- YAML
<ide> changes:
<ide> Synchronously changes owner and group of a file. Returns `undefined`.
<ide> This is the synchronous version of [`fs.chown()`][].
<ide>
<del>See also: chown(2)
<add>See also: chown(2).
<ide>
<ide> ## fs.close(fd, callback)
<ide> <!-- YAML
<ide> given to the completion callback.
<ide> If the file referred to by the file descriptor was larger than `len` bytes, only
<ide> the first `len` bytes will be retained in the file.
<ide>
<del>For example, the following program retains only the first four bytes of the file
<add>For example, the following program retains only the first four bytes of the
<add>file:
<ide>
<ide> ```js
<ide> console.log(fs.readFileSync('temp.txt', 'utf8'));
<ide> changes:
<ide> Asynchronously creates a directory. No arguments other than a possible exception
<ide> are given to the completion callback.
<ide>
<del>See also: mkdir(2)
<add>See also: mkdir(2).
<ide>
<ide> ## fs.mkdirSync(path[, mode])
<ide> <!-- YAML
<ide> changes:
<ide> Synchronously creates a directory. Returns `undefined`.
<ide> This is the synchronous version of [`fs.mkdir()`][].
<ide>
<del>See also: mkdir(2)
<add>See also: mkdir(2).
<ide>
<ide> ## fs.mkdtemp(prefix[, options], callback)
<ide> <!-- YAML
<ide> fs.unlink('path/file.txt', (err) => {
<ide> `fs.unlink()` will not work on a directory, empty or otherwise. To remove a
<ide> directory, use [`fs.rmdir()`][].
<ide>
<del>See also: unlink(2)
<add>See also: unlink(2).
<ide>
<ide> ## fs.unlinkSync(path)
<ide> <!-- YAML
<ide><path>doc/api/http.md
<ide> added: v0.7.8
<ide> Emitted when the underlying socket times out from inactivity. This only notifies
<ide> that the socket has been idle. The request must be aborted manually.
<ide>
<del>See also: [`request.setTimeout()`][]
<add>See also: [`request.setTimeout()`][].
<ide>
<ide> ### Event: 'upgrade'
<ide> <!-- YAML
<ide> added: v0.3.0
<ide>
<ide> * {net.Socket}
<ide>
<del>See [`request.socket`][]
<add>See [`request.socket`][].
<ide>
<ide> ### request.end([data[, encoding]][, callback])
<ide> <!-- YAML
<ide> automatically. Note that the callback must take care to consume the response
<ide> data for reasons stated in [`http.ClientRequest`][] section.
<ide>
<ide> The `callback` is invoked with a single argument that is an instance of
<del>[`http.IncomingMessage`][]
<add>[`http.IncomingMessage`][].
<ide>
<ide> JSON Fetching Example:
<ide>
<ide><path>doc/api/http2.md
<ide> protocol is available on the host `'example.org'` on TCP/IP port 81. The
<ide> host and port *must* be contained within the quote (`"`) characters.
<ide>
<ide> Multiple alternatives may be specified, for instance: `'h2="example.org:81",
<del>h2=":82"'`
<add>h2=":82"'`.
<ide>
<ide> The protocol identifier (`'h2'` in the examples) may be any valid
<ide> [ALPN Protocol ID][].
<ide><path>doc/api/https.md
<ide> Makes a request to a secure web server.
<ide> The following additional `options` from [`tls.connect()`][] are also accepted:
<ide> `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,
<ide> `honorCipherOrder`, `key`, `passphrase`, `pfx`, `rejectUnauthorized`,
<del>`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`
<add>`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`.
<ide>
<ide> `options` can be an object, a string, or a [`URL`][] object. If `options` is a
<ide> string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][]
<ide><path>doc/api/modules.md
<ide> this, assign the desired export object to `module.exports`. Note that assigning
<ide> the desired object to `exports` will simply rebind the local `exports` variable,
<ide> which is probably not what is desired.
<ide>
<del>For example suppose we were making a module called `a.js`
<add>For example suppose we were making a module called `a.js`:
<ide>
<ide> ```js
<ide> const EventEmitter = require('events');
<ide> setTimeout(() => {
<ide> }, 1000);
<ide> ```
<ide>
<del>Then in another file we could do
<add>Then in another file we could do:
<ide>
<ide> ```js
<ide> const a = require('./a');
<ide><path>doc/api/n-api.md
<ide> napi_status napi_set_named_property(napi_env env,
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<ide> This method is equivalent to calling [`napi_set_property`][] with a `napi_value`
<del>created from the string passed in as `utf8Name`
<add>created from the string passed in as `utf8Name`.
<ide>
<ide> #### napi_get_named_property
<ide> <!-- YAML
<ide> napi_status napi_get_named_property(napi_env env,
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<ide> This method is equivalent to calling [`napi_get_property`][] with a `napi_value`
<del>created from the string passed in as `utf8Name`
<add>created from the string passed in as `utf8Name`.
<ide>
<ide> #### napi_has_named_property
<ide> <!-- YAML
<ide> napi_status napi_has_named_property(napi_env env,
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<ide> This method is equivalent to calling [`napi_has_property`][] with a `napi_value`
<del>created from the string passed in as `utf8Name`
<add>created from the string passed in as `utf8Name`.
<ide>
<ide> #### napi_set_element
<ide> <!-- YAML
<ide><path>doc/api/net.md
<ide> added: v0.1.90
<ide>
<ide> * Returns: {Object}
<ide>
<del>Returns the bound address, the address family name, and port of the server
<del>as reported by the operating system if listening on an IP socket.
<del>Useful to find which port was assigned when getting an OS-assigned address.
<del>Returns an object with `port`, `family`, and `address` properties:
<del>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
<add>Returns the bound `address`, the address `family` name, and `port` of the server
<add>as reported by the operating system if listening on an IP socket
<add>(useful to find which port was assigned when getting an OS-assigned address):
<add>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
<ide>
<ide> For a server listening on a pipe or UNIX domain socket, the name is returned
<ide> as a string.
<ide> added: v0.1.90
<ide>
<ide> Emitted when the write buffer becomes empty. Can be used to throttle uploads.
<ide>
<del>See also: the return values of `socket.write()`
<add>See also: the return values of `socket.write()`.
<ide>
<ide> ### Event: 'end'
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> Emitted if the socket times out from inactivity. This is only to notify that
<ide> the socket has been idle. The user must manually close the connection.
<ide>
<del>See also: [`socket.setTimeout()`][]
<add>See also: [`socket.setTimeout()`][].
<ide>
<ide> ### socket.address()
<ide> <!-- YAML
<ide> added: v0.1.90
<ide>
<ide> * Returns: {Object}
<ide>
<del>Returns the bound address, the address family name and port of the
<del>socket as reported by the operating system. Returns an object with
<del>three properties, e.g.
<add>Returns the bound `address`, the address `family` name and `port` of the
<add>socket as reported by the operating system:
<ide> `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
<ide>
<ide> ### socket.bufferSize
<ide> client.on('end', () => {
<ide> ```
<ide>
<ide> To connect on the socket `/tmp/echo.sock` the second line would just be
<del>changed to
<add>changed to:
<ide>
<ide> ```js
<ide> const client = net.createConnection({ path: '/tmp/echo.sock' });
<ide> $ telnet localhost 8124
<ide> ```
<ide>
<ide> To listen on the socket `/tmp/echo.sock` the third line from the last would
<del>just be changed to
<add>just be changed to:
<ide>
<ide> ```js
<ide> server.listen('/tmp/echo.sock', () => {
<ide><path>doc/api/os.md
<ide> The properties available on the assigned network address object include:
<ide> is `IPv6`)
<ide> * `cidr` {string} The assigned IPv4 or IPv6 address with the routing prefix
<ide> in CIDR notation. If the `netmask` is invalid, this property is set
<del> to `null`
<add> to `null`.
<ide>
<ide> <!-- eslint-skip -->
<ide> ```js
<ide><path>doc/api/process.md
<ide> command-line option can be used to suppress the default console output but the
<ide> `'warning'` event will still be emitted by the `process` object.
<ide>
<ide> The following example illustrates the warning that is printed to `stderr` when
<del>too many listeners have been added to an event
<add>too many listeners have been added to an event:
<ide>
<ide> ```txt
<ide> $ node
<ide><path>doc/api/readline.md
<ide> The `'pause'` event is emitted when one of the following occur:
<ide>
<ide> * The `input` stream is paused.
<ide> * The `input` stream is not paused and receives the `'SIGCONT'` event. (See
<del> events [`'SIGTSTP'`][] and [`'SIGCONT'`][])
<add> events [`'SIGTSTP'`][] and [`'SIGCONT'`][].)
<ide>
<ide> The listener function is called without passing any arguments.
<ide>
<ide><path>doc/api/repl.md
<ide> The following special commands are supported by all REPL instances:
<ide> `> .save ./file/to/save.js`
<ide> * `.load` - Load a file into the current REPL session.
<ide> `> .load ./file/to/load.js`
<del>* `.editor` - Enter editor mode (`<ctrl>-D` to finish, `<ctrl>-C` to cancel)
<add>* `.editor` - Enter editor mode (`<ctrl>-D` to finish, `<ctrl>-C` to cancel).
<ide>
<ide> <!-- eslint-skip -->
<ide> ```js
<ide> By starting a REPL from a Unix socket-based server instead of stdin, it is
<ide> possible to connect to a long-running Node.js process without restarting it.
<ide>
<ide> For an example of running a "full-featured" (`terminal`) REPL over
<del>a `net.Server` and `net.Socket` instance, see: https://gist.github.com/2209310
<add>a `net.Server` and `net.Socket` instance, see:
<add>[https://gist.github.com/2209310](https://gist.github.com/2209310).
<ide>
<del>For an example of running a REPL instance over [curl(1)][],
<del>see: https://gist.github.com/2053342
<add>For an example of running a REPL instance over [curl(1)][], see:
<add>[https://gist.github.com/2053342](https://gist.github.com/2053342).
<ide>
<ide> [`--experimental-repl-await`]: cli.html#cli_experimental_repl_await
<ide> [`readline.InterfaceCompleter`]: readline.html#readline_use_of_the_completer_function
<ide><path>doc/api/stream.md
<ide> The workaround in this situation is to call the
<ide> ```js
<ide> // Workaround
<ide> net.createServer((socket) => {
<del>
<ide> socket.on('end', () => {
<ide> socket.end('The message was received but was not processed.\n');
<ide> });
<ide>
<ide> // start the flow of data, discarding it.
<ide> socket.resume();
<del>
<ide> }).listen(1337);
<ide> ```
<ide>
<ide><path>doc/api/synopsis.md
<ide> $ node hello-world.js
<ide> An output like this should appear in the terminal to indicate Node.js
<ide> server is running:
<ide>
<del> ```console
<del> Server running at http://127.0.0.1:3000/
<del> ````
<add>```console
<add>Server running at http://127.0.0.1:3000/
<add>```
<ide>
<ide> Now, open any preferred web browser and visit `http://127.0.0.1:3000`.
<ide>
<ide><path>doc/api/tls.md
<ide> added: v3.0.0
<ide> * Returns: {Buffer}
<ide>
<ide> Returns a `Buffer` instance holding the keys currently used for
<del>encryption/decryption of the [TLS Session Tickets][]
<add>encryption/decryption of the [TLS Session Tickets][].
<ide>
<ide> ### server.listen()
<ide>
<ide> added: v0.11.4
<ide>
<ide> * Returns: {Object}
<ide>
<del>Returns the bound address, the address family name, and port of the
<del>underlying socket as reported by the operating system. Returns an
<del>object with three properties, e.g.
<del>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
<add>Returns the bound `address`, the address `family` name, and `port` of the
<add>underlying socket as reported by the operating system:
<add>`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
<ide>
<ide> ### tlsSocket.authorizationError
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> Returns an object representing the cipher name. The `version` key is a legacy
<ide> field which always contains the value `'TLSv1/SSLv3'`.
<ide>
<del>For example: `{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }`
<add>For example: `{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }`.
<ide>
<ide> See `SSL_CIPHER_get_name()` in
<ide> https://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_name.html for more
<ide> ephemeral. As this is only supported on a client socket; `null` is returned
<ide> if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The
<ide> `name` property is available only when type is 'ECDH'.
<ide>
<del>For Example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`
<add>For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.
<ide>
<ide> ### tlsSocket.getFinished()
<ide> <!-- YAML
<ide> const options = {
<ide>
<ide> // This is necessary only if using the client certificate authentication.
<ide> requestCert: true,
<del>
<ide> };
<ide>
<ide> const server = tls.createServer(options, (socket) => {
<ide> changes:
<ide> * `session` {Buffer} An optional `Buffer` instance containing a TLS session.
<ide> * `requestOCSP` {boolean} If `true`, specifies that the OCSP status request
<ide> extension will be added to the client hello and an `'OCSPResponse'` event
<del> will be emitted on the socket before establishing a secure communication
<add> will be emitted on the socket before establishing a secure communication.
<ide>
<ide> Creates a new secure pair object with two streams, one of which reads and writes
<ide> the encrypted data and the other of which reads and writes the cleartext data.
<ide><path>doc/api/url.md
<ide> double slashes (if present) and precedes the `host` component, delimited by an
<ide> ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`,
<ide> with the `[:{password}]` portion being optional.
<ide>
<del>For example: `'user:pass'`
<add>For example: `'user:pass'`.
<ide>
<ide> #### urlObject.hash
<ide>
<ide> The `hash` property consists of the "fragment" portion of the URL including
<ide> the leading ASCII hash (`#`) character.
<ide>
<del>For example: `'#hash'`
<add>For example: `'#hash'`.
<ide>
<ide> #### urlObject.host
<ide>
<ide> The `host` property is the full lower-cased host portion of the URL, including
<ide> the `port` if specified.
<ide>
<del>For example: `'sub.host.com:8080'`
<add>For example: `'sub.host.com:8080'`.
<ide>
<ide> #### urlObject.hostname
<ide>
<ide> The `hostname` property is the lower-cased host name portion of the `host`
<ide> component *without* the `port` included.
<ide>
<del>For example: `'sub.host.com'`
<add>For example: `'sub.host.com'`.
<ide>
<ide> #### urlObject.href
<ide>
<ide> The `href` property is the full URL string that was parsed with both the
<ide> `protocol` and `host` components converted to lower-case.
<ide>
<del>For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`
<add>For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`.
<ide>
<ide> #### urlObject.path
<ide>
<ide> The `path` property is a concatenation of the `pathname` and `search`
<ide> components.
<ide>
<del>For example: `'/p/a/t/h?query=string'`
<add>For example: `'/p/a/t/h?query=string'`.
<ide>
<ide> No decoding of the `path` is performed.
<ide>
<ide> is everything following the `host` (including the `port`) and before the start
<ide> of the `query` or `hash` components, delimited by either the ASCII question
<ide> mark (`?`) or hash (`#`) characters.
<ide>
<del>For example `'/p/a/t/h'`
<add>For example `'/p/a/t/h'`.
<ide>
<ide> No decoding of the path string is performed.
<ide>
<ide> #### urlObject.port
<ide>
<ide> The `port` property is the numeric port portion of the `host` component.
<ide>
<del>For example: `'8080'`
<add>For example: `'8080'`.
<ide>
<ide> #### urlObject.protocol
<ide>
<ide> The `protocol` property identifies the URL's lower-cased protocol scheme.
<ide>
<del>For example: `'http:'`
<add>For example: `'http:'`.
<ide>
<ide> #### urlObject.query
<ide>
<ide> question mark (`?`), or an object returned by the [`querystring`][] module's
<ide> `parse()` method. Whether the `query` property is a string or object is
<ide> determined by the `parseQueryString` argument passed to `url.parse()`.
<ide>
<del>For example: `'query=string'` or `{'query': 'string'}`
<add>For example: `'query=string'` or `{'query': 'string'}`.
<ide>
<ide> If returned as a string, no decoding of the query string is performed. If
<ide> returned as an object, both keys and values are decoded.
<ide> returned as an object, both keys and values are decoded.
<ide> The `search` property consists of the entire "query string" portion of the
<ide> URL, including the leading ASCII question mark (`?`) character.
<ide>
<del>For example: `'?query=string'`
<add>For example: `'?query=string'`.
<ide>
<ide> No decoding of the query string is performed.
<ide>
<ide><path>doc/api/util.md
<ide> Since `null` has a special meaning as the first argument to a callback, if a
<ide> wrapped function rejects a `Promise` with a falsy value as a reason, the value
<ide> is wrapped in an `Error` with the original value stored in a field named
<ide> `reason`.
<del> ```js
<del> function fn() {
<del> return Promise.reject(null);
<del> }
<del> const callbackFunction = util.callbackify(fn);
<ide>
<del> callbackFunction((err, ret) => {
<del> // When the Promise was rejected with `null` it is wrapped with an Error and
<del> // the original value is stored in `reason`.
<del> err && err.hasOwnProperty('reason') && err.reason === null; // true
<del> });
<del> ```
<add>```js
<add>function fn() {
<add> return Promise.reject(null);
<add>}
<add>const callbackFunction = util.callbackify(fn);
<add>
<add>callbackFunction((err, ret) => {
<add> // When the Promise was rejected with `null` it is wrapped with an Error and
<add> // the original value is stored in `reason`.
<add> err && err.hasOwnProperty('reason') && err.reason === null; // true
<add>});
<add>```
<ide>
<ide> ## util.debuglog(section)
<ide> <!-- YAML
<ide> stream.on('data', (data) => {
<ide> stream.write('It works!'); // Received data: "It works!"
<ide> ```
<ide>
<del>ES6 example using `class` and `extends`
<add>ES6 example using `class` and `extends`:
<ide>
<ide> ```js
<ide> const EventEmitter = require('events');
<ide><path>doc/api/vm.md
<ide> const code = `
<ide> })`;
<ide>
<ide> vm.runInThisContext(code)(require);
<del> ```
<add>```
<ide>
<ide> The `require()` in the above case shares the state with the context it is
<ide> passed from. This may introduce risks when untrusted code is executed, e.g.
<ide><path>doc/api/zlib.md
<ide> ignored by the decompression classes.
<ide> * `strategy` {integer} (compression only)
<ide> * `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only,
<ide> empty dictionary by default)
<del>* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`)
<add>* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.)
<ide>
<ide> See the description of `deflateInit2` and `inflateInit2` at
<ide> <https://zlib.net/manual.html#Advanced> for more information on these. | 26 |
Javascript | Javascript | add test for amp errors during auto prerendering | 9993092ddd82a8892c112dd1b06c3f0532ec3c83 | <ide><path>test/integration/amp-export-validation/test/index.test.js
<ide> const appDir = join(__dirname, '../')
<ide> const outDir = join(appDir, 'out')
<ide> const nextConfig = new File(join(appDir, 'next.config.js'))
<ide>
<add>let buildOutput
<add>
<ide> describe('AMP Validation on Export', () => {
<ide> beforeAll(async () => {
<del> await nextBuild(appDir)
<add> const { stdout = '', stderr = '' } = await nextBuild(appDir, [], {
<add> stdout: true,
<add> stderr: true
<add> })
<ide> await nextExport(appDir, { outdir: outDir })
<add> buildOutput = stdout + stderr
<add> })
<add>
<add> it('should have shown errors during build', async () => {
<add> expect(buildOutput).toMatch(
<add> /error.*The tag 'img' may only appear as a descendant of tag 'noscript'. Did you mean 'amp-img'\?/
<add> )
<add> expect(buildOutput).toMatch(
<add> /error.*The tag 'img' may only appear as a descendant of tag 'noscript'. Did you mean 'amp-img'\?/
<add> )
<add> expect(buildOutput).toMatch(
<add> /warn.*The tag 'amp-video extension \.js script' is missing/
<add> )
<ide> })
<ide>
<ide> it('should export AMP pages', async () => { | 1 |
Ruby | Ruby | change video preview format from png to jpg | b60ee86d9469e4119cb8900e4bd78a04c86e6f1f | <ide><path>activestorage/lib/active_storage/previewer/video_previewer.rb
<ide> def self.accept?(blob)
<ide> def preview
<ide> download_blob_to_tempfile do |input|
<ide> draw_relevant_frame_from input do |output|
<del> yield io: output, filename: "#{blob.filename.base}.png", content_type: "image/png"
<add> yield io: output, filename: "#{blob.filename.base}.jpg", content_type: "image/jpeg"
<ide> end
<ide> end
<ide> end
<ide>
<ide> private
<ide> def draw_relevant_frame_from(file, &block)
<del> draw ffmpeg_path, "-i", file.path, "-y", "-vcodec", "png",
<del> "-vf", "thumbnail", "-vframes", "1", "-f", "image2", "-", &block
<add> draw ffmpeg_path, "-i", file.path, "-y", "-vframes", "1", "-f", "image2", "-", &block
<ide> end
<ide>
<ide> def ffmpeg_path
<ide><path>activestorage/test/models/preview_test.rb
<ide> class ActiveStorage::PreviewTest < ActiveSupport::TestCase
<ide> preview = blob.preview(resize: "640x280").processed
<ide>
<ide> assert_predicate preview.image, :attached?
<del> assert_equal "video.png", preview.image.filename.to_s
<del> assert_equal "image/png", preview.image.content_type
<add> assert_equal "video.jpg", preview.image.filename.to_s
<add> assert_equal "image/jpeg", preview.image.content_type
<ide>
<ide> image = read_image(preview.image)
<ide> assert_equal 640, image.width
<ide><path>activestorage/test/previewer/video_previewer_test.rb
<ide> class ActiveStorage::Previewer::VideoPreviewerTest < ActiveSupport::TestCase
<ide>
<ide> test "previewing an MP4 video" do
<ide> ActiveStorage::Previewer::VideoPreviewer.new(@blob).preview do |attachable|
<del> assert_equal "image/png", attachable[:content_type]
<del> assert_equal "video.png", attachable[:filename]
<add> assert_equal "image/jpeg", attachable[:content_type]
<add> assert_equal "video.jpg", attachable[:filename]
<ide>
<ide> image = MiniMagick::Image.read(attachable[:io])
<ide> assert_equal 640, image.width
<ide> assert_equal 480, image.height
<add> assert_equal "image/jpeg", image.mime_type
<ide> end
<ide> end
<ide> end | 3 |
Ruby | Ruby | remove debugging markers (oops) | df8d22a29b3dfb4313d0b983e92e6683f5df809f | <ide><path>Library/Homebrew/cli/args.rb
<ide> def resolve_keg(name)
<ide> require "formula"
<ide> require "missing_formula"
<ide>
<del> puts 1
<ide> raise UsageError if name.blank?
<ide>
<del> puts 2
<ide> rack = Formulary.to_rack(name.downcase)
<ide>
<del> puts 3
<ide> dirs = rack.directory? ? rack.subdirs : []
<ide> raise NoSuchKegError, rack.basename if dirs.empty?
<ide>
<del> puts 4
<ide> linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename
<ide> opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}"
<ide>
<del> puts 5
<ide> begin
<ide> if opt_prefix.symlink? && opt_prefix.directory?
<ide> Keg.new(opt_prefix.resolved_path) | 1 |
Text | Text | replace require() with reference links in http2.md | 07e7ad941bcf1b3b441ed0478381bee48339880c | <ide><path>doc/api/http2.md
<ide> Then `request.url` will be:
<ide> '/status?name=ryan'
<ide> ```
<ide>
<del>To parse the url into its parts, `require('url').parse(request.url)`
<del>can be used:
<add>To parse the url into its parts, [`url.parse(request.url)`][`url.parse()`].
<ide>
<ide> ```console
<ide> $ node
<del>> require('url').parse('/status?name=ryan')
<add>> url.parse('/status?name=ryan')
<ide> Url {
<ide> protocol: null,
<ide> slashes: null,
<ide> Url {
<ide> ```
<ide>
<ide> To obtain the parameters from the query string, use the
<del>`require('querystring').parse()` function or pass
<del>`true` as the second argument to `require('url').parse()`.
<add>[`querystring.parse()`][] function or pass
<add>`true` as the second argument to [`url.parse()`][].
<ide>
<ide> ```console
<ide> $ node
<del>> require('url').parse('/status?name=ryan', true)
<add>> url.parse('/status?name=ryan', true)
<ide> Url {
<ide> protocol: null,
<ide> slashes: null,
<ide> you need to implement any fall-back behaviour yourself.
<ide> [`net.Socket.prototype.unref()`]: net.html#net_socket_unref
<ide> [`net.Socket`]: net.html#net_class_net_socket
<ide> [`net.connect()`]: net.html#net_net_connect
<add>[`querystring.parse()`]: querystring.html#querystring_querystring_parse_str_sep_eq_options
<ide> [`request.authority`]: #http2_request_authority
<ide> [`request.socket`]: #http2_request_socket
<ide> [`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
<ide> you need to implement any fall-back behaviour yourself.
<ide> [`tls.TLSSocket`]: tls.html#tls_class_tls_tlssocket
<ide> [`tls.connect()`]: tls.html#tls_tls_connect_options_callback
<ide> [`tls.createServer()`]: tls.html#tls_tls_createserver_options_secureconnectionlistener
<add>[`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
<ide> [`writable.writableFinished`]: stream.html#stream_writable_writablefinished
<ide> [error code]: #error_codes
<ide> [Sensitive headers]: #http2-sensitive-headers | 1 |
Python | Python | fix typo in comment | ee4d6fdd4034272bd45b40632dcee89d2cf0ff24 | <ide><path>examples/training/train_textcat.py
<ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000):
<ide> # add label to text classifier
<ide> textcat.add_label('POSITIVE')
<ide>
<del> # load the IMBD dataset
<add> # load the IMDB dataset
<ide> print("Loading IMDB data...")
<ide> (train_texts, train_cats), (dev_texts, dev_cats) = load_data(limit=n_texts)
<ide> print("Using {} examples ({} training, {} evaluation)" | 1 |
Ruby | Ruby | simplify optlink method | 548d66be59d8c44eccae72c85f2996b3df0cd57a | <ide><path>Library/Homebrew/keg.rb
<ide> def link mode=OpenStruct.new
<ide> end
<ide>
<ide> def optlink
<del> if opt_record.symlink?
<del> opt_record.delete
<del> elsif opt_record.directory?
<del> opt_record.rmdir
<del> elsif opt_record.exist?
<del> opt_record.delete
<del> end
<add> opt_record.delete if opt_record.symlink? || opt_record.exist?
<ide> make_relative_symlink(opt_record, path)
<ide> end
<ide> | 1 |
Javascript | Javascript | fix tests for windows | 9596bf045d527e27608ac4b7b2990a4e6846fdeb | <ide><path>scripts/codegen/__tests__/generate-artifacts-executor-test.js
<ide> describe('delete empty files and folders', () => {
<ide> });
<ide>
<ide> it("when path is folder and it's empty, removes it", () => {
<del> const targetFolder = 'build/';
<add> const targetFolder = 'build';
<ide> const content = [];
<ide>
<ide> let statSyncInvocationCount = 0;
<ide> describe('delete empty files and folders', () => {
<ide> });
<ide>
<ide> it("when path is folder and it's not empty, removes only empty folders and files", () => {
<del> const targetFolder = 'build/';
<add> const targetFolder = 'build';
<ide> const content = ['emptyFolder', 'emptyFile', 'notEmptyFile'];
<ide>
<del> const files = ['build/emptyFile', 'build/notEmptyFile'];
<add> const files = [
<add> path.normalize('build/emptyFile'),
<add> path.normalize('build/notEmptyFile'),
<add> ];
<ide>
<ide> const emptyContent = [];
<del> const fileSizes = {
<del> 'build/emptyFile': 0,
<del> 'build/notEmptyFile': 32,
<del> };
<add> let fileSizes = {};
<add> fileSizes[path.normalize('build/emptyFile')] = 0;
<add> fileSizes[path.normalize('build/notEmptyFile')] = 32;
<ide>
<ide> let statSyncInvocation = [];
<ide> let rmSyncInvocation = [];
<ide> describe('delete empty files and folders', () => {
<ide>
<ide> underTest._cleanupEmptyFilesAndFolders(targetFolder);
<ide> expect(statSyncInvocation).toEqual([
<del> 'build/',
<del> 'build/emptyFolder',
<del> 'build/emptyFile',
<del> 'build/notEmptyFile',
<add> path.normalize('build'),
<add> path.normalize('build/emptyFolder'),
<add> path.normalize('build/emptyFile'),
<add> path.normalize('build/notEmptyFile'),
<ide> ]);
<ide> expect(readdirInvocation).toEqual([
<del> 'build/',
<del> 'build/emptyFolder',
<del> 'build/emptyFolder',
<del> 'build/',
<add> path.normalize('build'),
<add> path.normalize('build/emptyFolder'),
<add> path.normalize('build/emptyFolder'),
<add> path.normalize('build'),
<ide> ]);
<del> expect(rmSyncInvocation).toEqual(['build/emptyFile']);
<del> expect(rmdirSyncInvocation).toEqual(['build/emptyFolder']);
<add> expect(rmSyncInvocation).toEqual([path.normalize('build/emptyFile')]);
<add> expect(rmdirSyncInvocation).toEqual([path.normalize('build/emptyFolder')]);
<ide> });
<ide>
<ide> it('when path is folder and it contains only empty folders, removes everything', () => {
<del> const targetFolder = 'build/';
<add> const targetFolder = 'build';
<ide> const content = ['emptyFolder1', 'emptyFolder2'];
<ide> const emptyContent = [];
<ide>
<ide> describe('delete empty files and folders', () => {
<ide>
<ide> underTest._cleanupEmptyFilesAndFolders(targetFolder);
<ide> expect(statSyncInvocation).toEqual([
<del> 'build/',
<del> 'build/emptyFolder1',
<del> 'build/emptyFolder2',
<add> path.normalize('build'),
<add> path.normalize('build/emptyFolder1'),
<add> path.normalize('build/emptyFolder2'),
<ide> ]);
<ide> expect(readdirInvocation).toEqual([
<del> 'build/',
<del> 'build/emptyFolder1',
<del> 'build/emptyFolder1',
<del> 'build/emptyFolder2',
<del> 'build/emptyFolder2',
<del> 'build/',
<add> path.normalize('build'),
<add> path.normalize('build/emptyFolder1'),
<add> path.normalize('build/emptyFolder1'),
<add> path.normalize('build/emptyFolder2'),
<add> path.normalize('build/emptyFolder2'),
<add> path.normalize('build'),
<ide> ]);
<ide> expect(rmSyncInvocation).toEqual([]);
<ide> expect(rmdirSyncInvocation).toEqual([
<del> 'build/emptyFolder1',
<del> 'build/emptyFolder2',
<del> 'build/',
<add> path.normalize('build/emptyFolder1'),
<add> path.normalize('build/emptyFolder2'),
<add> path.normalize('build'),
<ide> ]);
<ide> });
<ide> }); | 1 |
Text | Text | add sakthipriyan to the ctc | 3c1e5b366f92a51824c5ae0b6f20cd290cf54a0e | <ide><path>README.md
<ide> more information about the governance of the Node.js project, see
<ide> **Shigeki Ohtsu** <ohtsu@iij.ad.jp>
<ide> * [TheAlphaNerd](https://github.com/TheAlphaNerd) -
<ide> **Myles Borins** <myles.borins@gmail.com>
<add>* [thefourtheye](https://github.com/thefourtheye) -
<add>**Sakthipriyan Vairamani** <thechargingvolcano@gmail.com>
<ide> * [trevnorris](https://github.com/trevnorris) -
<ide> **Trevor Norris** <trev.norris@gmail.com>
<ide> * [Trott](https://github.com/Trott) -
<ide> more information about the governance of the Node.js project, see
<ide> **Michaël Zasso** <targos@protonmail.com>
<ide> * [tellnes](https://github.com/tellnes) -
<ide> **Christian Tellnes** <christian@tellnes.no>
<del>* [thefourtheye](https://github.com/thefourtheye) -
<del>**Sakthipriyan Vairamani** <thechargingvolcano@gmail.com>
<ide> * [thekemkid](https://github.com/thekemkid) -
<ide> **Glen Keane** <glenkeane.94@gmail.com>
<ide> * [thlorenz](https://github.com/thlorenz) - | 1 |
PHP | PHP | add push/pop onto stringtemplate | e85e241278444c43f5870daf2ee1b87487dfd578 | <ide><path>src/View/StringTemplate.php
<ide> class StringTemplate {
<ide> 'compactAttribute' => '{{name}}="{{value}}"',
<ide> ];
<ide>
<add>/**
<add> * A stack of template sets that have been stashed temporarily.
<add> *
<add> * @var
<add> */
<add> protected $_configStack = [];
<add>
<ide> /**
<ide> * Contains the list of compiled templates
<ide> *
<ide> public function __construct(array $config = []) {
<ide> $this->config($config);
<ide> }
<ide>
<add>/**
<add> * Push the current templates onto the template stack.
<add> *
<add> * @return void
<add> */
<add> public function push() {
<add> $this->_configStack[] = $this->_config;
<add> }
<add>
<add>/**
<add> * Restore the most recently pushed set of templates.
<add> *
<add> * Restoring templates will invalidate all compiled templates.
<add> *
<add> * @return void
<add> */
<add> public function pop() {
<add> if (empty($this->_configStack)) {
<add> return;
<add> }
<add> $this->_config = array_pop($this->_configStack);
<add> $this->_compiled = [];
<add> }
<add>
<ide> /**
<ide> * Registers a list of templates by name
<ide> *
<ide> * ### Example:
<ide> *
<ide> * {{{
<ide> * $templater->add([
<del> * 'link' => '<a href="{{url}}">{{title}}</a>'
<del> * 'button' => '<button>{{text}}</button>'
<add> * 'link' => '<a href="{{url}}">{{title}}</a>'
<add> * 'button' => '<button>{{text}}</button>'
<ide> * ]);
<ide> * }}}
<ide> *
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide> public function testCopiledInfoRefresh() {
<ide> $this->assertEquals([null, null], $this->template->compile('link'));
<ide> }
<ide>
<add>/**
<add> * test push/pop templates.
<add> *
<add> * @return void
<add> */
<add> public function testPushPopTemplates() {
<add> $this->template->add(['name' => '{{name}} is my name']);
<add> $this->assertNull($this->template->push());
<add>
<add> $this->template->add(['name' => 'my name']);
<add> $this->assertEquals('my name', $this->template->get('name'));
<add>
<add> $this->assertNull($this->template->pop());
<add> $this->assertEquals('{{name}} is my name', $this->template->get('name'));
<add>
<add> $this->assertNull($this->template->pop());
<add> $this->assertNull($this->template->pop());
<add> }
<add>
<ide> } | 2 |
Python | Python | use the same name everywhere | 819c851a3f5befb51ee55b84108d2a0d8819765e | <ide><path>libcloud/compute/drivers/vcloud.py
<ide> def reboot_node(self, node):
<ide> else:
<ide> return False
<ide>
<del> def ex_deploy_node(self, node, force_customization=False):
<add> def ex_deploy_node(self, node, ex_force_customization=False):
<ide> """
<ide> Deploys existing node. Equal to vApp "start" operation.
<ide>
<ide> :param node: The node to be deployed
<ide> :type node: :class:`Node`
<ide>
<del> :param force_customization: Used to specify whether to force
<del> customization on deployment,
<del> if not set default value is False.
<del> :type force_customization: ``bool``
<add> :param ex_force_customization: Used to specify whether to force
<add> customization on deployment,
<add> if not set default value is False.
<add> :type ex_force_customization: ``bool``
<ide>
<ide> :rtype: :class:`Node`
<ide> """
<del> if force_customization:
<add> if ex_force_customization:
<ide> vms = self._get_vm_elements(node.id)
<ide> for vm in vms:
<ide> self._ex_deploy_node_or_vm(vm.get('href'),
<del> force_customization=True)
<add> ex_force_customization=True)
<ide> else:
<ide> self._ex_deploy_node_or_vm(node.id)
<ide>
<ide> res = self.connection.request(get_url_path(node.id))
<ide> return self._to_node(res.object)
<ide>
<del> def _ex_deploy_node_or_vm(self, vapp_or_vm_path, force_customization=False):
<add> def _ex_deploy_node_or_vm(self, vapp_or_vm_path,
<add> ex_force_customization=False):
<ide> data = {'powerOn': 'true',
<del> 'forceCustomization': str(force_customization).lower(),
<add> 'forceCustomization': str(ex_force_customization).lower(),
<ide> 'xmlns': 'http://www.vmware.com/vcloud/v1.5'}
<ide> deploy_xml = ET.Element('DeployVAppParams', data)
<ide> path = get_url_path(vapp_or_vm_path) | 1 |
Text | Text | update the readme | d22005489b25d63c927040ad03ff12170fa592b1 | <ide><path>official/vision/detection/README.md
<ide> python3 ~/models/official/vision/detection/main.py \
<ide> --params_override="{ type: retinanet, train: { checkpoint: { path: ${RESNET_CHECKPOINT?}, prefix: resnet50/ }, train_file_pattern: ${TRAIN_FILE_PATTERN?} }, eval: { val_json_file: ${VAL_JSON_FILE?}, eval_file_pattern: ${EVAL_FILE_PATTERN?} } }"
<ide> ```
<ide>
<del>The pre-trained ResNet-50 checkpoint can be found here:
<add>The pre-trained ResNet-50 checkpoint can be downloaded [here](https://storage.cloud.google.com/cloud-tpu-checkpoints/model-garden-vision/detection/resnet50-2018-02-07.tar.gz).
<add>
<add>Note: The ResNet implementation under
<add>[detection/](https://github.com/tensorflow/models/tree/master/official/vision/detection)
<add>is currently different from the one under
<add>[classification/](https://github.com/tensorflow/models/tree/master/official/vision/image_classification),
<add>so the checkpoints are not compatible.
<add>We will unify the implementation soon.
<add>
<ide>
<del>```
<del>https://storage.cloud.google.com/cloud-tpu-checkpoints/model-garden-vision/detection/resnet50-2018-02-07.tar.gz
<del>```
<ide>
<ide> ### Train a custom RetinaNet using the config file.
<ide>
<ide> python3 ~/models/official/vision/detection/main.py \
<ide> --params_override="{train: { checkpoint: { path: ${RESNET_CHECKPOINT}, prefix: resnet50/ }, train_file_pattern: ${TRAIN_FILE_PATTERN} }, eval: { val_json_file: ${VAL_JSON_FILE}, eval_file_pattern: ${EVAL_FILE_PATTERN} } }"
<ide> ```
<ide>
<del>The pre-trained ResNet-50 checkpoint can be found here:
<add>The pre-trained ResNet-50 checkpoint can be downloaded [here](https://storage.cloud.google.com/cloud-tpu-checkpoints/model-garden-vision/detection/resnet50-2018-02-07.tar.gz).
<add>
<add>Note: The ResNet implementation under
<add>[detection/](https://github.com/tensorflow/models/tree/master/official/vision/detection)
<add>is currently different from the one under
<add>[classification/](https://github.com/tensorflow/models/tree/master/official/vision/image_classification),
<add>so the checkpoints are not compatible.
<add>We will unify the implementation soon.
<ide>
<del>```
<del>https://storage.cloud.google.com/cloud-tpu-checkpoints/model-garden-vision/detection/resnet50-2018-02-07.tar.gz
<del>```
<ide>
<ide> ### Train a custom Mask R-CNN using the config file.
<ide> | 1 |
Text | Text | add readme file for the api directory | 3e2b97ef26467228f6018e19f517ed535e107026 | <ide><path>api/README.md
<add>This directory contains code pertaining to the Docker API:
<add>
<add> - Used by the docker client when comunicating with the docker deamon
<add>
<add> - Used by third party tools wishing to interface with the docker deamon | 1 |
Ruby | Ruby | update .pluck documentation on uniq | 03f35fc439fc4a10c1bc8af710b2c7e2467acd9d | <ide><path>activerecord/lib/active_record/relation/calculations.rb
<ide> def calculate(operation, column_name)
<ide> # # SELECT people.id, people.name FROM people
<ide> # # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
<ide> #
<del> # Person.pluck('DISTINCT role')
<add> # Person.uniq.pluck(:role)
<ide> # # SELECT DISTINCT role FROM people
<ide> # # => ['admin', 'member', 'guest']
<ide> # | 1 |
Javascript | Javascript | fix links in docs | 6faeb97515dc19686cbd6025f1557ff5fd4083b9 | <ide><path>pages/src/docs/src/Defs.js
<ide> var TypeDef = React.createClass({
<ide> case TypeKind.Type:
<ide> var qualifiedType = (type.qualifier || []).concat([type.name]);
<ide> var qualifiedTypeName = qualifiedType.join('.');
<del> var def = qualifiedType.reduce(
<add> var def = qualifiedTypeName.split('.').reduce(
<ide> (def, name) => def && def.module && def.module[name],
<ide> defs.Immutable
<ide> );
<ide><path>pages/src/docs/src/TypeDocumentation.js
<ide> var TypeDoc = React.createClass({
<ide> function getTypePropMap(def) {
<ide> var map = {};
<ide> def && def.extends && def.extends.forEach(e => {
<del> var superModule = defs.Immutable.module[e.name];
<add> var superModule = defs.Immutable;
<add> e.name.split('.').forEach(part => {
<add> superModule =
<add> superModule && superModule.module && superModule.module[part];
<add> });
<ide> var superInterface = superModule && superModule.interface;
<ide> if (superInterface) {
<ide> var interfaceMap = Seq(superInterface.typeParams) | 2 |
Javascript | Javascript | accommodate line chunking in windows | 807ede70fa52a88604e939dbffbb7b09daeb0beb | <ide><path>lib/internal/inspector/_inspect.js
<ide> function runScript(script, scriptArgs, inspectHost, inspectPort, childPrint) {
<ide> const child = spawn(process.execPath, args);
<ide> child.stdout.setEncoding('utf8');
<ide> child.stderr.setEncoding('utf8');
<del> child.stdout.on('data', childPrint);
<del> child.stderr.on('data', childPrint);
<add> child.stdout.on('data', (chunk) => childPrint(chunk, 'stdout'));
<add> child.stderr.on('data', (chunk) => childPrint(chunk, 'stderr'));
<ide>
<ide> let output = '';
<ide> function waitForListenHint(text) {
<ide> class NodeInspector {
<ide> return this.client.connect(port, host)
<ide> .then(() => {
<ide> debuglog('connection established');
<del> this.stdout.write(' ok');
<add> this.stdout.write(' ok\n');
<ide> }, (error) => {
<ide> debuglog('connect failed', error);
<ide> // If it's failed to connect 10 times then print failed message
<ide> class NodeInspector {
<ide> });
<ide> };
<ide>
<del> this.print(`connecting to ${host}:${port} ..`, true);
<add> this.print(`connecting to ${host}:${port} ..`, false);
<ide> return attemptConnect();
<ide> });
<ide> }
<ide> class NodeInspector {
<ide> }
<ide> }
<ide>
<del> print(text, oneline = false) {
<add> print(text, appendNewline = false) {
<ide> this.clearLine();
<del> this.stdout.write(oneline ? text : `${text}\n`);
<add> this.stdout.write(appendNewline ? `${text}\n` : text);
<ide> }
<ide>
<del> childPrint(text) {
<del> this.print(
<del> text.toString()
<del> .split(/\r\n|\r|\n/g)
<del> .filter((chunk) => !!chunk)
<del> .map((chunk) => `< ${chunk}`)
<del> .join('\n')
<del> );
<del> if (!this.paused) {
<del> this.repl.displayPrompt(true);
<add> #stdioBuffers = {stdout: '', stderr: ''};
<add> childPrint(text, which) {
<add> const lines = (this.#stdioBuffers[which] + text)
<add> .split(/\r\n|\r|\n/g);
<add>
<add> this.#stdioBuffers[which] = '';
<add>
<add> if (lines[lines.length - 1] !== '') {
<add> this.#stdioBuffers[which] = lines.pop();
<add> }
<add>
<add> const textToPrint = lines.map((chunk) => `< ${chunk}`).join('\n');
<add>
<add> if (lines.length) {
<add> this.print(textToPrint, true);
<add> if (!this.paused) {
<add> this.repl.displayPrompt(true);
<add> }
<ide> }
<del> if (/Waiting for the debugger to disconnect\.\.\.\n$/.test(text)) {
<add>
<add> if (textToPrint.endsWith('Waiting for the debugger to disconnect...\n')) {
<ide> this.killChild();
<ide> }
<ide> }
<ide><path>lib/internal/inspector/inspect_repl.js
<ide> function createRepl(inspector) {
<ide> return util.inspect(value, INSPECT_OPTIONS);
<ide> }
<ide>
<del> function print(value, oneline = false) {
<add> function print(value, addNewline = true) {
<ide> const text = typeof value === 'string' ? value : inspect(value);
<del> return inspector.print(text, oneline);
<add> return inspector.print(text, addNewline);
<ide> }
<ide>
<ide> function getCurrentLocation() {
<ide> function createRepl(inspector) {
<ide> if (finished) {
<ide> print('Heap snaphost prepared.');
<ide> } else {
<del> print(`Heap snapshot: ${done}/${total}`, true);
<add> print(`Heap snapshot: ${done}/${total}`, false);
<ide> }
<ide> }
<ide> function onChunk({ chunk }) {
<ide> sizeWritten += chunk.length;
<ide> writer.write(chunk);
<del> print(`Writing snapshot: ${sizeWritten}`, true);
<add> print(`Writing snapshot: ${sizeWritten}`, false);
<ide> }
<ide> function onResolve() {
<ide> writer.end(() => {
<ide> function createRepl(inspector) {
<ide> HeapProfiler.on('reportHeapSnapshotProgress', onProgress);
<ide> HeapProfiler.on('addHeapSnapshotChunk', onChunk);
<ide>
<del> print('Heap snapshot: 0/0', true);
<add> print('Heap snapshot: 0/0', false);
<ide> HeapProfiler.takeHeapSnapshot({ reportProgress: true })
<ide> .then(onResolve, onReject);
<ide> }); | 2 |
Java | Java | improve @nullable annotation | ad2c0f8410e3b8642e65545afe77e38614069b08 | <ide><path>spring-core/src/main/java/org/springframework/lang/Nullable.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<del>import javax.annotation.meta.TypeQualifierDefault;
<add>import javax.annotation.Nonnull;
<add>import javax.annotation.meta.TypeQualifierNickname;
<add>import javax.annotation.meta.When;
<ide>
<ide> /**
<ide> * Leverage JSR 305 meta-annotations to define the annotated element could be null
<ide> * @see javax.annotation.Nullable
<ide> */
<ide> @Documented
<del>@javax.annotation.Nullable
<add>@TypeQualifierNickname
<add>@Nonnull(when= When.MAYBE)
<ide> @Target({ElementType.METHOD, ElementType.PARAMETER})
<del>@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER})
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> public @interface Nullable {
<ide> } | 1 |
Go | Go | improve docstrings and small cleanup in client | a68ae4a2d95b1ff143025a435195af0f1ab30ace | <ide><path>client/client.go
<ide> For example, to list running containers (the equivalent of "docker ps"):
<ide> package client // import "github.com/docker/docker/client"
<ide>
<ide> import (
<del> "errors"
<ide> "fmt"
<add> "net"
<ide> "net/http"
<ide> "net/url"
<ide> "os"
<ide> import (
<ide> "github.com/docker/docker/api/types/versions"
<ide> "github.com/docker/go-connections/sockets"
<ide> "github.com/docker/go-connections/tlsconfig"
<add> "github.com/pkg/errors"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func CheckRedirect(req *http.Request, via []*http.Request) error {
<ide> }
<ide>
<ide> // NewEnvClient initializes a new API client based on environment variables.
<del>// Use DOCKER_HOST to set the url to the docker server.
<del>// Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
<del>// Use DOCKER_CERT_PATH to load the TLS certificates from.
<del>// Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
<del>// deprecated: use NewClientWithOpts(FromEnv)
<add>// See FromEnv for a list of support environment variables.
<add>//
<add>// Deprecated: use NewClientWithOpts(FromEnv)
<ide> func NewEnvClient() (*Client, error) {
<ide> return NewClientWithOpts(FromEnv)
<ide> }
<ide>
<del>// FromEnv enhance the default client with values from environment variables
<add>// FromEnv configures the client with values from environment variables.
<add>//
<add>// Supported environment variables:
<add>// DOCKER_HOST to set the url to the docker server.
<add>// DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.
<add>// DOCKER_CERT_PATH to load the TLS certificates from.
<add>// DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.
<ide> func FromEnv(c *Client) error {
<del> var httpClient *http.Client
<ide> if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" {
<ide> options := tlsconfig.Options{
<ide> CAFile: filepath.Join(dockerCertPath, "ca.pem"),
<ide> func FromEnv(c *Client) error {
<ide> return err
<ide> }
<ide>
<del> httpClient = &http.Client{
<del> Transport: &http.Transport{
<del> TLSClientConfig: tlsc,
<del> },
<add> c.client = &http.Client{
<add> Transport: &http.Transport{TLSClientConfig: tlsc},
<ide> CheckRedirect: CheckRedirect,
<ide> }
<del> WithHTTPClient(httpClient)(c)
<ide> }
<ide>
<del> host := os.Getenv("DOCKER_HOST")
<del> if host != "" {
<del> // WithHost will create an API client if it doesn't exist
<add> if host := os.Getenv("DOCKER_HOST"); host != "" {
<ide> if err := WithHost(host)(c); err != nil {
<ide> return err
<ide> }
<ide> }
<del> version := os.Getenv("DOCKER_API_VERSION")
<del> if version != "" {
<add>
<add> if version := os.Getenv("DOCKER_API_VERSION"); version != "" {
<ide> c.version = version
<ide> c.manualOverride = true
<ide> }
<ide> return nil
<ide> }
<ide>
<add>// WithTLSClientConfig applies a tls config to the client transport.
<add>func WithTLSClientConfig(cacertPath, certPath, keyPath string) func(*Client) error {
<add> return func(c *Client) error {
<add> opts := tlsconfig.Options{
<add> CAFile: cacertPath,
<add> CertFile: certPath,
<add> KeyFile: keyPath,
<add> ExclusiveRootPools: true,
<add> }
<add> config, err := tlsconfig.Client(opts)
<add> if err != nil {
<add> return errors.Wrap(err, "failed to create tls config")
<add> }
<add> if transport, ok := c.client.Transport.(*http.Transport); ok {
<add> transport.TLSClientConfig = config
<add> return nil
<add> }
<add> return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport)
<add> }
<add>}
<add>
<add>// WithDialer applies the dialer.DialContext to the client transport. This can be
<add>// used to set the Timeout and KeepAlive settings of the client.
<add>func WithDialer(dialer *net.Dialer) func(*Client) error {
<add> return func(c *Client) error {
<add> if transport, ok := c.client.Transport.(*http.Transport); ok {
<add> transport.DialContext = dialer.DialContext
<add> return nil
<add> }
<add> return errors.Errorf("cannot apply dialer to transport: %T", c.client.Transport)
<add> }
<add>}
<add>
<ide> // WithVersion overrides the client version with the specified one
<ide> func WithVersion(version string) func(*Client) error {
<ide> return func(c *Client) error {
<ide> func WithVersion(version string) func(*Client) error {
<ide> }
<ide> }
<ide>
<del>// WithHost overrides the client host with the specified one, creating a new
<del>// http client if one doesn't exist
<add>// WithHost overrides the client host with the specified one.
<ide> func WithHost(host string) func(*Client) error {
<ide> return func(c *Client) error {
<ide> hostURL, err := ParseHostURL(host)
<ide> func WithHost(host string) func(*Client) error {
<ide> c.proto = hostURL.Scheme
<ide> c.addr = hostURL.Host
<ide> c.basePath = hostURL.Path
<del> if c.client == nil {
<del> client, err := defaultHTTPClient(host)
<del> if err != nil {
<del> return err
<del> }
<del> return WithHTTPClient(client)(c)
<del> }
<ide> if transport, ok := c.client.Transport.(*http.Transport); ok {
<ide> return sockets.ConfigureTransport(transport, c.proto, c.addr)
<ide> }
<del> return fmt.Errorf("cannot apply host to http transport")
<add> return errors.Errorf("cannot apply host to transport: %T", c.client.Transport)
<ide> }
<ide> }
<ide>
<ide> func defaultHTTPClient(host string) (*http.Client, error) {
<ide> // It won't send any version information if the version number is empty. It is
<ide> // highly recommended that you set a version or your client may break if the
<ide> // server is upgraded.
<del>// deprecated: use NewClientWithOpts
<add>// Deprecated: use NewClientWithOpts
<ide> func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) {
<ide> return NewClientWithOpts(WithHost(host), WithVersion(version), WithHTTPClient(client), WithHTTPHeaders(httpHeaders))
<ide> }
<ide> func (cli *Client) CustomHTTPHeaders() map[string]string {
<ide> }
<ide>
<ide> // SetCustomHTTPHeaders that will be set on every HTTP request made by the client.
<add>// Deprecated: use WithHTTPHeaders when creating the client.
<ide> func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) {
<ide> cli.customHTTPHeaders = headers
<ide> }
<ide><path>integration/internal/request/client.go
<ide> package request // import "github.com/docker/docker/integration/internal/request
<ide>
<ide> import (
<ide> "fmt"
<del> "net"
<del> "net/http"
<ide> "testing"
<ide> "time"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/internal/test/environment"
<del> "github.com/docker/go-connections/sockets"
<del> "github.com/docker/go-connections/tlsconfig"
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide>
<ide> func NewAPIClient(t *testing.T, ops ...func(*client.Client) error) client.APICli
<ide> return clt
<ide> }
<ide>
<del>// NewTLSAPIClient returns a docker API client configured with the
<del>// provided TLS settings
<del>func NewTLSAPIClient(t *testing.T, host, cacertPath, certPath, keyPath string) (client.APIClient, error) {
<del> opts := tlsconfig.Options{
<del> CAFile: cacertPath,
<del> CertFile: certPath,
<del> KeyFile: keyPath,
<del> ExclusiveRootPools: true,
<del> }
<del> config, err := tlsconfig.Client(opts)
<del> require.Nil(t, err)
<del> tr := &http.Transport{
<del> TLSClientConfig: config,
<del> DialContext: (&net.Dialer{
<del> KeepAlive: 30 * time.Second,
<del> Timeout: 30 * time.Second,
<del> }).DialContext,
<del> }
<del> proto, addr, _, err := client.ParseHost(host)
<del> require.Nil(t, err)
<del>
<del> sockets.ConfigureTransport(tr, proto, addr)
<del>
<del> httpClient := &http.Client{
<del> Transport: tr,
<del> CheckRedirect: client.CheckRedirect,
<del> }
<del> return client.NewClientWithOpts(client.WithHost(host), client.WithHTTPClient(httpClient))
<del>}
<del>
<ide> // daemonTime provides the current time on the daemon host
<ide> func daemonTime(ctx context.Context, t *testing.T, client client.APIClient, testEnv *environment.Execution) time.Time {
<ide> if testEnv.IsLocalDaemon() {
<ide><path>integration/plugin/authz/authz_plugin_test.go
<ide> import (
<ide> eventtypes "github.com/docker/docker/api/types/events"
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/integration/internal/container"
<del> "github.com/docker/docker/integration/internal/request"
<ide> "github.com/docker/docker/internal/test/environment"
<ide> "github.com/docker/docker/pkg/authorization"
<ide> "github.com/gotestyourself/gotestyourself/skip"
<ide> func TestAuthZPluginTLS(t *testing.T) {
<ide> ctrl.reqRes.Allow = true
<ide> ctrl.resRes.Allow = true
<ide>
<del> client, err := request.NewTLSAPIClient(t, testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath)
<add> client, err := newTLSAPIClient(testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath)
<ide> require.Nil(t, err)
<ide>
<ide> _, err = client.ServerVersion(context.Background())
<ide> func TestAuthZPluginTLS(t *testing.T) {
<ide> require.Equal(t, "client", ctrl.resUser)
<ide> }
<ide>
<add>func newTLSAPIClient(host, cacertPath, certPath, keyPath string) (client.APIClient, error) {
<add> dialer := &net.Dialer{
<add> KeepAlive: 30 * time.Second,
<add> Timeout: 30 * time.Second,
<add> }
<add> return client.NewClientWithOpts(
<add> client.WithTLSClientConfig(cacertPath, certPath, keyPath),
<add> client.WithDialer(dialer),
<add> client.WithHost(host))
<add>}
<add>
<ide> func TestAuthZPluginDenyRequest(t *testing.T) {
<ide> defer setupTestV1(t)()
<ide> d.Start(t, "--authorization-plugin="+testAuthZPlugin) | 3 |
Javascript | Javascript | add sourcemap support for .mjs output files | 12762ff37fe882f11f6fa962a9e18632bcd482e6 | <ide><path>lib/SourceMapDevToolPlugin.js
<ide> class SourceMapDevToolPlugin {
<ide> const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
<ide> const requestShortener = compiler.requestShortener;
<ide> const options = this.options;
<del> options.test = options.test || /\.(js|css)($|\?)/i;
<add> options.test = options.test || /\.(m?js|css)($|\?)/i;
<ide>
<ide> const matchObject = ModuleFilenameHelpers.matchObject.bind(
<ide> undefined, | 1 |
Ruby | Ruby | fix syntax error with no us-ascii char | 9eb72ac78f15078c362cb4bc6cc42ddda182127b | <ide><path>activerecord/lib/active_record/validations.rb
<ide> module ActiveRecord
<ide> # puts invalid.record.errors
<ide> # end
<ide> class RecordInvalid < ActiveRecordError
<del> attr_reader :record # :nodoc:
<add> attr_reader :record # :nodoc:
<ide> def initialize(record) # :nodoc:
<ide> @record = record
<ide> errors = @record.errors.full_messages.join(", ") | 1 |
Javascript | Javascript | update plans in config | 08ec29fa1b5aa46b68c5286a3264f1f30d224424 | <ide><path>config/donation-settings.js
<ide> require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
<ide> // Configuration for client side
<ide> const durationsConfig = {
<ide> year: 'yearly',
<del> // month: 'monthly',
<add> // month: 'monthly', // We have disabled montly payments
<ide> onetime: 'one-time'
<ide> };
<ide> const amountsConfig = {
<ide> year: [100000, 25000, 6000],
<del> // month: [5000, 3500, 500],
<del> onetime: [100000, 25000, 3500]
<add> month: [5000, 3500, 500],
<add> onetime: [100000, 25000, 6000]
<ide> };
<ide> const defaultAmount = {
<ide> year: 6000,
<ide> const modalDefaultStateConfig = {
<ide>
<ide> // Configuration for server side
<ide> const durationKeysConfig = ['year', 'month', 'onetime'];
<del>const donationOneTimeConfig = [100000, 25000, 3500];
<add>const donationOneTimeConfig = [100000, 25000, 6000];
<ide> const donationSubscriptionConfig = {
<ide> duration: {
<ide> year: 'Yearly',
<ide> month: 'Monthly'
<ide> },
<ide> plans: {
<del> year: [100000, 25000, 3500],
<add> year: [100000, 25000, 6000],
<ide> month: [5000, 3500, 500]
<ide> }
<ide> }; | 1 |
Mixed | Go | add system time to /info | 2977fd2b7aed42008ca2ad90dcd8fec5ead4e86b | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> if remoteInfo.Exists("NGoroutines") {
<ide> fmt.Fprintf(cli.out, "Goroutines: %d\n", remoteInfo.GetInt("NGoroutines"))
<ide> }
<add> if remoteInfo.Exists("SystemTime") {
<add> t, err := remoteInfo.GetTime("SystemTime")
<add> if err != nil {
<add> log.Errorf("Error reading system time: %v", err)
<add> } else {
<add> fmt.Fprintf(cli.out, "System Time: %s\n", t.Format(time.UnixDate))
<add> }
<add> }
<ide> if remoteInfo.Exists("NEventsListener") {
<ide> fmt.Fprintf(cli.out, "EventsListeners: %d\n", remoteInfo.GetInt("NEventsListener"))
<ide> }
<ide><path>daemon/info.go
<ide> package daemon
<ide> import (
<ide> "os"
<ide> "runtime"
<add> "time"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/autogen/dockerversion"
<ide> func (daemon *Daemon) CmdInfo(job *engine.Job) engine.Status {
<ide> v.SetBool("Debug", os.Getenv("DEBUG") != "")
<ide> v.SetInt("NFd", utils.GetTotalUsedFds())
<ide> v.SetInt("NGoroutines", runtime.NumGoroutine())
<add> v.Set("SystemTime", time.Now().Format(time.RFC3339Nano))
<ide> v.Set("ExecutionDriver", daemon.ExecutionDriver().Name())
<ide> v.SetInt("NEventsListener", env.GetInt("count"))
<ide> v.Set("KernelVersion", kernelVersion)
<ide><path>docs/sources/reference/api/docker_remote_api.md
<ide> This endpoint now returns `Os`, `Arch` and `KernelVersion`.
<ide> **New!**
<ide> You can set ulimit settings to be used within the container.
<ide>
<del>`Get /info`
<add>`GET /info`
<ide>
<ide> **New!**
<del>Add return value `HttpProxy`,`HttpsProxy` and `NoProxy` to this entrypoint.
<add>This endpoint now returns `SystemTime`, `HttpProxy`,`HttpsProxy` and `NoProxy`.
<ide>
<ide>
<ide> ## v1.17
<ide><path>docs/sources/reference/api/docker_remote_api_v1.18.md
<ide> Display system-wide information
<ide> "Debug":false,
<ide> "NFd": 11,
<ide> "NGoroutines":21,
<add> "SystemTime": "2015-03-10T11:11:23.730591467-07:00"
<ide> "NEventsListener":0,
<ide> "InitPath":"/usr/bin/docker",
<ide> "InitSha1":"",
<ide><path>docs/sources/reference/commandline/cli.md
<ide> For example:
<ide> Debug mode (client): true
<ide> Fds: 10
<ide> Goroutines: 9
<add> System Time: Tue Mar 10 18:38:57 UTC 2015
<ide> EventsListeners: 0
<ide> Init Path: /usr/bin/docker
<ide> Docker Root Dir: /var/lib/docker
<ide><path>engine/env.go
<ide> import (
<ide> "io"
<ide> "strconv"
<ide> "strings"
<add> "time"
<ide>
<ide> "github.com/docker/docker/utils"
<ide> )
<ide> func (env *Env) SetBool(key string, value bool) {
<ide> }
<ide> }
<ide>
<add>func (env *Env) GetTime(key string) (time.Time, error) {
<add> t, err := time.Parse(time.RFC3339Nano, env.Get(key))
<add> return t, err
<add>}
<add>
<add>func (env *Env) SetTime(key string, t time.Time) {
<add> env.Set(key, t.Format(time.RFC3339Nano))
<add>}
<add>
<ide> func (env *Env) GetInt(key string) int {
<ide> return int(env.GetInt64(key))
<ide> }
<ide><path>engine/env_test.go
<ide> import (
<ide> "bytes"
<ide> "encoding/json"
<ide> "testing"
<add> "time"
<ide>
<ide> "github.com/docker/docker/pkg/testutils"
<ide> )
<ide> func TestSetenvBool(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestSetenvTime(t *testing.T) {
<add> job := mkJob(t, "dummy")
<add>
<add> now := time.Now()
<add> job.SetenvTime("foo", now)
<add> if val, err := job.GetenvTime("foo"); err != nil {
<add> t.Fatalf("GetenvTime failed to parse: %v", err)
<add> } else {
<add> nowStr := now.Format(time.RFC3339)
<add> valStr := val.Format(time.RFC3339)
<add> if nowStr != valStr {
<add> t.Fatalf("GetenvTime returns incorrect value: %s, Expected: %s", valStr, nowStr)
<add> }
<add> }
<add>
<add> job.Setenv("bar", "Obviously I'm not a date")
<add> if val, err := job.GetenvTime("bar"); err == nil {
<add> t.Fatalf("GetenvTime was supposed to fail, instead returned: %s", val)
<add> }
<add>}
<add>
<ide> func TestSetenvInt(t *testing.T) {
<ide> job := mkJob(t, "dummy")
<ide>
<ide><path>engine/job.go
<ide> func (job *Job) SetenvBool(key string, value bool) {
<ide> job.env.SetBool(key, value)
<ide> }
<ide>
<add>func (job *Job) GetenvTime(key string) (value time.Time, err error) {
<add> return job.env.GetTime(key)
<add>}
<add>
<add>func (job *Job) SetenvTime(key string, value time.Time) {
<add> job.env.SetTime(key, value)
<add>}
<add>
<ide> func (job *Job) GetenvSubEnv(key string) *Env {
<ide> return job.env.GetSubEnv(key)
<ide> } | 8 |
PHP | PHP | respect local env | 75e792d61871780f75ecb4eb170826b0ba2f305e | <ide><path>src/Illuminate/Foundation/Console/ServeCommand.php
<ide> public function handle()
<ide> protected function startProcess()
<ide> {
<ide> $process = new Process($this->serverCommand(), null, collect($_ENV)->mapWithKeys(function ($value, $key) {
<del> return [$key => false];
<add> return $key === 'APP_ENV'
<add> ? [$key => $value]
<add> : [$key => false];
<ide> })->all());
<ide>
<ide> $process->start(function ($type, $buffer) { | 1 |
Javascript | Javascript | prefer safe initializer by name storage | 0cdbf59ab65f3d9e7235cfb6176ad5944390ea5d | <ide><path>packages/ember-application/lib/system/application.js
<ide> import {
<ide> import EmberHandlebars from "ember-handlebars-compiler";
<ide>
<ide> var ContainerDebugAdapter;
<add>function props(obj) {
<add> var properties = [];
<add>
<add> for (var key in obj) {
<add> properties.push(key);
<add> }
<add>
<add> return properties;
<add>}
<ide>
<ide> /**
<ide> An instance of `Ember.Application` is the starting point for every Ember
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> @method runInitializers
<ide> */
<ide> runInitializers: function() {
<del> var initializers = get(this.constructor, 'initializers');
<add> var initializersByName = get(this.constructor, 'initializers');
<add> var initializers = props(initializersByName);
<ide> var container = this.__container__;
<ide> var graph = new DAG();
<ide> var namespace = this;
<ide> var name, initializer;
<ide>
<del> for (name in initializers) {
<del> initializer = initializers[name];
<add> for (var i = 0; i < initializers.length; i++) {
<add> initializer = initializersByName[initializers[i]];
<ide> graph.addEdges(initializer.name, initializer.initialize, initializer.before, initializer.after);
<ide> }
<ide>
<ide> graph.topsort(function (vertex) {
<ide> var initializer = vertex.value;
<del> Ember.assert("No application initializer named '"+vertex.name+"'", initializer);
<add> Ember.assert("No application initializer named '" + vertex.name + "'", initializer);
<ide> initializer(container, namespace);
<ide> });
<ide> },
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> });
<ide>
<ide> Application.reopenClass({
<del> initializers: {},
<add> initializers: Object.create(null),
<ide>
<ide> /**
<ide> Initializer receives an object which has the following attributes: | 1 |
Go | Go | use "local" secret paths based on the secretid | 37ce91ddd60e50a8bcd7ac3a7ba858f94c28c51e | <ide><path>container/container.go
<ide> func (container *Container) SecretMountPath() string {
<ide> return filepath.Join(container.Root, "secrets")
<ide> }
<ide>
<del>func (container *Container) getLocalSecretPath(r *swarmtypes.SecretReference) string {
<del> return filepath.Join(container.SecretMountPath(), filepath.Base(r.File.Name))
<add>// SecretFilePath returns the path to the location of a secret on the host.
<add>func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) string {
<add> return filepath.Join(container.SecretMountPath(), secretRef.SecretID)
<ide> }
<ide>
<ide> func getSecretTargetPath(r *swarmtypes.SecretReference) string {
<ide><path>container/container_unix.go
<ide> func (container *Container) IpcMounts() []Mount {
<ide> return mounts
<ide> }
<ide>
<del>// SecretMounts returns the mount for the secret path
<add>// SecretMounts returns the mounts for the secret path.
<ide> func (container *Container) SecretMounts() []Mount {
<ide> var mounts []Mount
<ide> for _, r := range container.SecretReferences {
<del> // secrets are created in the SecretMountPath at a single level
<del> // i.e. /var/run/secrets/foo
<del> srcPath := container.getLocalSecretPath(r)
<add> if r.File == nil {
<add> continue
<add> }
<ide> mounts = append(mounts, Mount{
<del> Source: srcPath,
<add> Source: container.SecretFilePath(*r),
<ide> Destination: getSecretTargetPath(r),
<ide> Writable: false,
<ide> })
<ide><path>container/container_windows.go
<ide> func (container *Container) IpcMounts() []Mount {
<ide> return nil
<ide> }
<ide>
<del>// SecretMounts returns the mount for the secret path
<add>// SecretMounts returns the mounts for the secret path
<ide> func (container *Container) SecretMounts() []Mount {
<ide> return nil
<ide> }
<ide><path>daemon/container_operations_unix.go
<ide> func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
<ide> return fmt.Errorf("secret target type is not a file target")
<ide> }
<ide>
<del> // secrets are created in the SecretMountPath at a single level
<del> // i.e. /var/run/secrets/foo
<del> fPath := filepath.Join(localMountPath, filepath.Base(s.File.Name))
<add> // secrets are created in the SecretMountPath on the host, at a
<add> // single level
<add> fPath := c.SecretFilePath(*s)
<ide> if err := idtools.MkdirAllAs(filepath.Dir(fPath), 0700, rootUID, rootGID); err != nil {
<ide> return errors.Wrap(err, "error creating secret mount path")
<ide> } | 4 |
Ruby | Ruby | do less work inside chdir blocks | 53b7d45de8f38d1998e5c23a77064ae3df4be522 | <ide><path>Library/Homebrew/test/test_pathname.rb
<ide> def test_install_removes_original
<ide> end
<ide>
<ide> def setup_install_test
<del> cd @src do
<del> (@src+'a.txt').write 'This is sample file a.'
<del> (@src+'b.txt').write 'This is sample file b.'
<del> yield
<del> end
<add> (@src+'a.txt').write 'This is sample file a.'
<add> (@src+'b.txt').write 'This is sample file b.'
<add> cd(@src) { yield }
<ide> end
<ide>
<ide> def test_install
<ide> setup_install_test do
<ide> @dst.install 'a.txt'
<del>
<del> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<del> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed."
<ide> end
<add>
<add> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<add> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed."
<ide> end
<ide>
<ide> def test_install_list
<ide> setup_install_test do
<ide> @dst.install %w[a.txt b.txt]
<del>
<del> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<del> assert_predicate @dst+"b.txt", :exist?, "b.txt was not installed"
<ide> end
<add>
<add> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<add> assert_predicate @dst+"b.txt", :exist?, "b.txt was not installed"
<ide> end
<ide>
<ide> def test_install_glob
<ide> setup_install_test do
<ide> @dst.install Dir['*.txt']
<del>
<del> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<del> assert_predicate @dst+"b.txt", :exist?, "b.txt was not installed"
<ide> end
<add>
<add> assert_predicate @dst+"a.txt", :exist?, "a.txt was not installed"
<add> assert_predicate @dst+"b.txt", :exist?, "b.txt was not installed"
<ide> end
<ide>
<ide> def test_install_directory
<ide> setup_install_test do
<ide> mkdir_p 'bin'
<ide> mv Dir['*.txt'], 'bin'
<del>
<ide> @dst.install 'bin'
<del>
<del> assert_predicate @dst+"bin/a.txt", :exist?, "a.txt was not installed"
<del> assert_predicate @dst+"bin/b.txt", :exist?, "b.txt was not installed"
<ide> end
<add>
<add> assert_predicate @dst+"bin/a.txt", :exist?, "a.txt was not installed"
<add> assert_predicate @dst+"bin/b.txt", :exist?, "b.txt was not installed"
<ide> end
<ide>
<ide> def test_install_rename
<ide> setup_install_test do
<ide> @dst.install 'a.txt' => 'c.txt'
<del>
<del> assert_predicate @dst+"c.txt", :exist?, "c.txt was not installed"
<del> refute_predicate @dst+"a.txt", :exist?, "a.txt was installed but not renamed"
<del> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed"
<ide> end
<add>
<add> assert_predicate @dst+"c.txt", :exist?, "c.txt was not installed"
<add> refute_predicate @dst+"a.txt", :exist?, "a.txt was installed but not renamed"
<add> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed"
<ide> end
<ide>
<ide> def test_install_rename_more
<ide> setup_install_test do
<ide> @dst.install({'a.txt' => 'c.txt', 'b.txt' => 'd.txt'})
<del>
<del> assert_predicate @dst+"c.txt", :exist?, "c.txt was not installed"
<del> assert_predicate @dst+"d.txt", :exist?, "d.txt was not installed"
<del> refute_predicate @dst+"a.txt", :exist?, "a.txt was installed but not renamed"
<del> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed but not renamed"
<ide> end
<add>
<add> assert_predicate @dst+"c.txt", :exist?, "c.txt was not installed"
<add> assert_predicate @dst+"d.txt", :exist?, "d.txt was not installed"
<add> refute_predicate @dst+"a.txt", :exist?, "a.txt was installed but not renamed"
<add> refute_predicate @dst+"b.txt", :exist?, "b.txt was installed but not renamed"
<ide> end
<ide>
<ide> def test_install_rename_directory
<ide> setup_install_test do
<ide> mkdir_p 'bin'
<ide> mv Dir['*.txt'], 'bin'
<del>
<ide> @dst.install 'bin' => 'libexec'
<del>
<del> refute_predicate @dst+"bin", :exist?, "bin was installed but not renamed"
<del> assert_predicate @dst+"libexec/a.txt", :exist?, "a.txt was not installed"
<del> assert_predicate @dst+"libexec/b.txt", :exist?, "b.txt was not installed"
<ide> end
<add>
<add> refute_predicate @dst+"bin", :exist?, "bin was installed but not renamed"
<add> assert_predicate @dst+"libexec/a.txt", :exist?, "a.txt was not installed"
<add> assert_predicate @dst+"libexec/b.txt", :exist?, "b.txt was not installed"
<ide> end
<ide>
<ide> def test_install_symlink
<ide> setup_install_test do
<ide> mkdir_p 'bin'
<ide> mv Dir['*.txt'], 'bin'
<add> end
<ide>
<del> @dst.install_symlink @src+'bin'
<del>
<del> assert_predicate @dst+"bin", :symlink?
<del> assert_predicate @dst+"bin", :directory?
<del> assert_predicate @dst+"bin/a.txt", :exist?
<del> assert_predicate @dst+"bin/b.txt", :exist?
<add> @dst.install_symlink @src+'bin'
<ide>
<del> assert_predicate (@dst+"bin").readlink, :relative?
<del> end
<add> assert_predicate @dst+"bin", :symlink?
<add> assert_predicate @dst+"bin", :directory?
<add> assert_predicate @dst+"bin/a.txt", :exist?
<add> assert_predicate @dst+"bin/b.txt", :exist?
<add> assert_predicate (@dst+"bin").readlink, :relative?
<ide> end
<ide>
<ide> def test_install_creates_intermediate_directories | 1 |
PHP | PHP | remove ini flag for memcached.sasl | f534945734353ff209e7824f80633f2ff6679e78 | <ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> public function init(array $config = [])
<ide> }
<ide>
<ide> if ($this->_config['username'] !== null && $this->_config['password'] !== null) {
<del> $sasl = method_exists($this->_Memcached, 'setSaslAuthData') && ini_get('memcached.use_sasl');
<add> $sasl = method_exists($this->_Memcached, 'setSaslAuthData');
<ide> if (!$sasl) {
<ide> throw new InvalidArgumentException(
<ide> 'Memcached extension is not build with SASL support' | 1 |
PHP | PHP | allow disabling of middleware (for test reasons) | 0f67cf19abc74ba5ee2bdc9c946b2bf62d85149c | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> protected function sendRequestThroughRouter($request)
<ide>
<ide> $this->verifySessionConfigurationIsValid();
<ide>
<add> $shouldSkipMiddleware = $this->app->bound('middleware.disable') &&
<add> $this->app->make('middleware.disable') === true;
<add>
<ide> return (new Pipeline($this->app))
<ide> ->send($request)
<del> ->through($this->middleware)
<add> ->through($shouldSkipMiddleware ? [] : $this->middleware)
<ide> ->then($this->dispatchToRouter());
<ide> }
<ide>
<ide><path>src/Illuminate/Routing/ControllerDispatcher.php
<ide> protected function callWithinStack($instance, $route, $request, $method)
<ide> {
<ide> $middleware = $this->getMiddleware($instance, $method);
<ide>
<add> $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
<add> $this->container->make('middleware.disable') === true;
<add>
<ide> // Here we will make a stack onion instance to execute this request in, which gives
<ide> // us the ability to define middlewares on controllers. We will return the given
<ide> // response back out so that "after" filters can be run after the middlewares.
<ide> return (new Pipeline($this->container))
<ide> ->send($request)
<del> ->through($middleware)
<add> ->through($shouldSkipMiddleware ? [] : $middleware)
<ide> ->then(function($request) use ($instance, $route, $method)
<ide> {
<ide> return $this->router->prepareResponse(
<ide><path>src/Illuminate/Routing/Router.php
<ide> protected function runRouteWithinStack(Route $route, Request $request)
<ide> {
<ide> $middleware = $this->gatherRouteMiddlewares($route);
<ide>
<add> $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
<add> $this->container->make('middleware.disable') === true;
<add>
<ide> return (new Pipeline($this->container))
<ide> ->send($request)
<del> ->through($middleware)
<add> ->through($shouldSkipMiddleware ? [] : $middleware)
<ide> ->then(function($request) use ($route)
<ide> {
<ide> return $this->prepareResponse( | 3 |
Python | Python | allow filterting contributors by release version | f75780f13cbffb992d1bfab7286492201e2a59aa | <ide><path>contrib/generate_contributor_list.py
<ide> GITHUB_URL = 'https://github.com/apache/libcloud/pull/%s'
<ide>
<ide>
<del>def parse_changes_file(file_path):
<add>def parse_changes_file(file_path, version=None):
<ide> """
<ide> Parse CHANGES file and return a dictionary with contributors.
<ide>
<ide> def parse_changes_file(file_path):
<ide> contributors_map = defaultdict(set)
<ide>
<ide> in_entry = False
<add> active_version = None
<ide> active_tickets = []
<ide>
<ide> with open(file_path, 'r') as fp:
<ide> for line in fp:
<ide> line = line.strip()
<ide>
<add> match = re.search(r'Changes with Apache Libcloud '
<add> '(\d+\.\d+\.\d+(-\w+)?).*?$', line)
<add>
<add> if match:
<add> active_version = match.groups()[0]
<add>
<add> if version and active_version != version:
<add> continue
<add>
<ide> if line.startswith('-') or line.startswith('*)'):
<ide> in_entry = True
<ide> active_tickets = []
<ide> def compare(item1, item2):
<ide> ' in a single image')
<ide> parser.add_argument('--changes-path', action='store',
<ide> help='Path to the changes file')
<add> parser.add_argument('--version', action='store',
<add> help='Only return contributors for the provided '
<add> 'version')
<ide> args = parser.parse_args()
<ide>
<del> contributors_map = parse_changes_file(file_path=args.changes_path)
<add> contributors_map = parse_changes_file(file_path=args.changes_path,
<add> version=args.version)
<ide> markdown = convert_to_markdown(contributors_map=contributors_map)
<ide>
<ide> print(markdown) | 1 |
Javascript | Javascript | add tracks length check for mmdhelper | 228257762a865c00a2463de1275d1dba8099b4f6 | <ide><path>examples/js/loaders/MMDLoader.js
<ide> THREE.MMDHelper.prototype = {
<ide> // the name of them begins with "_".
<ide> mesh.mixer.addEventListener( 'loop', function ( e ) {
<ide>
<del> if ( e.action._clip.tracks[ 0 ].name.indexOf( '.bones' ) !== 0 ) return;
<add> if ( e.action._clip.tracks.length > 0 &&
<add> e.action._clip.tracks[ 0 ].name.indexOf( '.bones' ) !== 0 ) return;
<ide>
<ide> var mesh = e.target._root;
<ide> mesh.looped = true;
<ide> THREE.MMDHelper.prototype = {
<ide>
<ide> var action = mesh.mixer.clipAction( clip );
<ide>
<del> if ( clip.tracks[ 0 ].name.indexOf( '.morphTargetInfluences' ) === 0 ) {
<add> if ( clip.tracks.length > 0 && clip.tracks[ 0 ].name.indexOf( '.morphTargetInfluences' ) === 0 ) {
<ide>
<ide> if ( ! foundMorphAnimation ) {
<ide> | 1 |
Python | Python | fix py3 syntax | 20cc77a1a466192fb2ea11f61f6cbf678f266b87 | <ide><path>numpy/linalg/_gufuncs_linalg.py
<ide>
<ide> """
<ide>
<del>from __future__ import division, absolute_import
<add>from __future__ import division, absolute_import, print_function
<ide>
<ide>
<ide> __all__ = ['inner1d', 'dotc1d', 'innerwt', 'matrix_multiply', 'det', 'slogdet',
<ide> def poinv(A, UPLO='L', **kw_args):
<ide>
<ide> if __name__ == "__main__":
<ide> import doctest
<del> print "Running doctests..."
<ide> doctest.testmod()
<ide><path>numpy/linalg/tests/test_gufuncs_linalg.py
<ide> Test functions for gufuncs_linalg module
<ide> Heavily inspired (ripped in part) test_linalg
<ide> """
<del>
<add>from __future__ import division, print_function
<ide>
<ide> ################################################################################
<ide> # The following functions are implemented in the module "gufuncs_linalg"
<ide> def do(self, a):
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> print 'testing gufuncs_linalg; gufuncs version: %s' % gula._impl.__version__
<add> print('testing gufuncs_linalg; gufuncs version: %s' % gula._impl.__version__)
<ide> run_module_suite() | 2 |
Javascript | Javascript | remove default press delay | 86ffb9c41e033f59599e01b7ad016706b5f62fc8 | <ide><path>Libraries/Pressability/Pressability.js
<ide> const isPressInSignal = signal =>
<ide> const isTerminalSignal = signal =>
<ide> signal === 'RESPONDER_TERMINATED' || signal === 'RESPONDER_RELEASE';
<ide>
<del>const DEFAULT_LONG_PRESS_DELAY_MS = 370; // 500 - 130
<del>const DEFAULT_PRESS_DELAY_MS = 130;
<add>const DEFAULT_LONG_PRESS_DELAY_MS = 500;
<ide> const DEFAULT_PRESS_RECT_OFFSETS = {
<ide> bottom: 30,
<ide> left: 20,
<ide> export default class Pressability {
<ide> this._touchState = 'NOT_RESPONDER';
<ide> this._receiveSignal('RESPONDER_GRANT', event);
<ide>
<del> const delayPressIn = normalizeDelay(
<del> this._config.delayPressIn,
<del> 0,
<del> DEFAULT_PRESS_DELAY_MS,
<del> );
<del>
<add> const delayPressIn = normalizeDelay(this._config.delayPressIn);
<ide> if (delayPressIn > 0) {
<ide> this._pressDelayTimeout = setTimeout(() => {
<ide> this._receiveSignal('DELAY', event);
<ide> export default class Pressability {
<ide> const delayLongPress = normalizeDelay(
<ide> this._config.delayLongPress,
<ide> 10,
<del> DEFAULT_LONG_PRESS_DELAY_MS,
<add> DEFAULT_LONG_PRESS_DELAY_MS - delayPressIn,
<ide> );
<ide> this._longPressDelayTimeout = setTimeout(() => {
<ide> this._handleLongPress(event);
<ide><path>Libraries/Pressability/__tests__/Pressability-test.js
<ide> describe('Pressability', () => {
<ide> expect(config.onLongPress).toBeCalled();
<ide> });
<ide>
<del> it('is called if pressed for 370ms after the press delay', () => {
<add> it('is called if pressed for 500ms after press started', () => {
<ide> const {config, handlers} = createMockPressability({
<ide> delayPressIn: 100,
<ide> });
<ide> describe('Pressability', () => {
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<ide> handlers.onResponderMove(createMockPressEvent('onResponderMove'));
<ide>
<del> jest.advanceTimersByTime(469);
<add> jest.advanceTimersByTime(499);
<ide> expect(config.onLongPress).not.toBeCalled();
<ide> jest.advanceTimersByTime(1);
<ide> expect(config.onLongPress).toBeCalled();
<ide> describe('Pressability', () => {
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<ide> handlers.onResponderMove(createMockPressEvent('onResponderMove'));
<ide>
<del> jest.advanceTimersByTime(139);
<add> jest.advanceTimersByTime(9);
<ide> expect(config.onLongPress).not.toBeCalled();
<ide> jest.advanceTimersByTime(1);
<ide> expect(config.onLongPress).toBeCalled();
<ide> describe('Pressability', () => {
<ide> const {config, handlers} = createMockPressability();
<ide>
<ide> handlers.onStartShouldSetResponder();
<del> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderGrant(
<add> createMockPressEvent({
<add> registrationName: 'onResponderGrant',
<add> pageX: 0,
<add> pageY: 0,
<add> }),
<add> );
<ide> handlers.onResponderMove(
<ide> createMockPressEvent({
<ide> registrationName: 'onResponderMove',
<ide> describe('Pressability', () => {
<ide>
<ide> // Subsequent long touch gesture should not carry over previous state.
<ide> handlers.onStartShouldSetResponder();
<del> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<add> handlers.onResponderGrant(
<add> createMockPressEvent({
<add> registrationName: 'onResponderGrant',
<add> pageX: 7,
<add> pageY: 8,
<add> }),
<add> );
<ide> handlers.onResponderMove(
<ide> // NOTE: Delta from (0, 0) is ~10.6 > 10, but should not matter.
<ide> createMockPressEvent({
<ide> describe('Pressability', () => {
<ide> expect(config.onPressIn).toBeCalled();
<ide> });
<ide>
<del> it('is called after the default delay by default', () => {
<add> it('is called immediately by default', () => {
<ide> const {config, handlers} = createMockPressability({
<ide> delayPressIn: null,
<ide> });
<ide> describe('Pressability', () => {
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<ide> handlers.onResponderMove(createMockPressEvent('onResponderMove'));
<ide>
<del> jest.advanceTimersByTime(129);
<del> expect(config.onPressIn).not.toBeCalled();
<del> jest.advanceTimersByTime(1);
<del> expect(config.onPressIn).toBeCalled();
<del> });
<del>
<del> it('falls back to the default delay if `delayPressIn` is omitted', () => {
<del> const {config, handlers} = createMockPressability({
<del> delayPressIn: null,
<del> });
<del>
<del> handlers.onStartShouldSetResponder();
<del> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<del> handlers.onResponderMove(createMockPressEvent('onResponderMove'));
<del>
<del> jest.advanceTimersByTime(129);
<del> expect(config.onPressIn).not.toBeCalled();
<del> jest.advanceTimersByTime(1);
<ide> expect(config.onPressIn).toBeCalled();
<ide> });
<ide>
<ide> describe('Pressability', () => {
<ide>
<ide> describe('onPressOut', () => {
<ide> it('is called after `onResponderRelease` before `delayPressIn`', () => {
<del> const {config, handlers} = createMockPressability();
<add> const {config, handlers} = createMockPressability({
<add> delayPressIn: Number.EPSILON,
<add> });
<ide>
<ide> handlers.onStartShouldSetResponder();
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<ide> describe('Pressability', () => {
<ide> });
<ide>
<ide> it('is called after `onResponderRelease` after `delayPressIn`', () => {
<del> const {config, handlers} = createMockPressability();
<add> const {config, handlers} = createMockPressability({
<add> delayPressIn: Number.EPSILON,
<add> });
<ide>
<ide> handlers.onStartShouldSetResponder();
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant'));
<ide> describe('Pressability', () => {
<ide> });
<ide>
<ide> it('is not called after `onResponderTerminate` before `delayPressIn`', () => {
<del> const {config, handlers} = createMockPressability();
<add> const {config, handlers} = createMockPressability({
<add> delayPressIn: Number.EPSILON,
<add> });
<ide>
<ide> handlers.onStartShouldSetResponder();
<ide> handlers.onResponderGrant(createMockPressEvent('onResponderGrant')); | 2 |
Ruby | Ruby | remove rendererbutils from ap (only av use it) | 21c5f2845de42fb2f5feee47d4270c18a4a4d5b0 | <ide><path>actionpack/test/abstract_unit.rb
<ide> def body_to_string(body)
<ide> extend self
<ide> end
<ide>
<del>module RenderERBUtils
<del> def view
<del> @view ||= begin
<del> path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
<del> view_paths = ActionView::PathSet.new([path])
<del> ActionView::Base.new(view_paths)
<del> end
<del> end
<del>
<del> def render_erb(string)
<del> @virtual_path = nil
<del>
<del> template = ActionView::Template.new(
<del> string.strip,
<del> "test template",
<del> ActionView::Template::Handlers::ERB,
<del> {})
<del>
<del> template.render(self, {}).strip
<del> end
<del>end
<del>
<ide> SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
<ide>
<ide> module ActionDispatch | 1 |
Text | Text | update contributing.md with process for doc fixes | 5a8d9acacbb8a2b9175da196cbaf8ff93bac28c8 | <ide><path>CONTRIBUTING.md
<ide> duplication of work, and help you to craft the change so that it is successfully
<ide> project.
<ide> * **Small Changes** can be crafted and submitted to [GitHub Repository][github] as a Pull Request.
<ide>
<add>
<add>## Want a Doc Fix?
<add>If you want to help improve the docs, it's a good idea to let others know what you're working on to
<add>minimize duplication of effort. Before starting, check out the issue queue for [Milestone:Docs Only with label type:docs](https://github.com/angular/angular.js/issues?labels=type%3A+docs&milestone=24&state=open).
<add>Comment on an issue to let others know what you're working on, or create a new issue if your work
<add>doesn't fit within the scope of any of the exisitng doc fix projects.
<add>
<add>For large fixes, please build and test the documentation before submitting the PR to be sure you haven't
<add>accidentally introduced any layout or formatting issues.
<add>
<add>If you're just making a small change, don't worry about filing an issue first. Use the friendly blue "Improve this doc" button at the top right of the doc page to fork the repository in-place and make a quick change on the fly.
<add>
<ide> ## Submission Guidelines
<ide>
<ide> ### Submitting an Issue | 1 |
Ruby | Ruby | add macos.lion? for macos_version == 10.7 | e3e7831b48b7dbcb435f5233adcff33f91aef3da | <ide><path>Library/Homebrew/utils.rb
<ide> def red; underline 31; end
<ide> def yellow; underline 33 ; end
<ide> def reset; escape 0; end
<ide> def em; underline 39; end
<del>
<add>
<ide> private
<ide> def color n
<ide> escape "0;#{n}"
<ide> def snow_leopard?
<ide> 10.6 <= MACOS_VERSION # Actually Snow Leopard or newer
<ide> end
<ide>
<add> def lion?
<add> 10.7 == MACOS_VERSION
<add> end
<add>
<ide> def prefer_64_bit?
<ide> Hardware.is_64_bit? and 10.6 <= MACOS_VERSION
<ide> end | 1 |
Text | Text | improve consistency of docs examples [ci skip] | 1fa6d6ba55e8d4c84db8d74a284fec1d60dc32c5 | <ide><path>website/docs/api/doc.md
<ide> compressed binary strings. The `Doc` object holds an array of `TokenC]` structs.
<ide> The Python-level `Token` and [`Span`](/api/span) objects are views of this
<ide> array, i.e. they don't own the data themselves.
<ide>
<add>## Doc.\_\_init\_\_ {#init tag="method"}
<add>
<add>Construct a `Doc` object. The most common way to get a `Doc` object is via the
<add>`nlp` object.
<add>
<ide> > #### Example
<ide> >
<ide> > ```python
<ide> array, i.e. they don't own the data themselves.
<ide> > doc = Doc(nlp.vocab, words=words, spaces=spaces)
<ide> > ```
<ide>
<del>## Doc.\_\_init\_\_ {#init tag="method"}
<del>
<del>Construct a `Doc` object. The most common way to get a `Doc` object is via the
<del>`nlp` object.
<del>
<ide> | Name | Type | Description |
<ide> | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<ide> | `vocab` | `Vocab` | A storage container for lexical types. |
<ide><path>website/docs/api/top-level.md
<ide> class. The data will be loaded in via
<ide> > nlp = spacy.load("/path/to/en") # unicode path
<ide> > nlp = spacy.load(Path("/path/to/en")) # pathlib Path
<ide> >
<del>> nlp = spacy.load("en", disable=["parser", "tagger"])
<add>> nlp = spacy.load("en_core_web_sm", disable=["parser", "tagger"])
<ide> > ```
<ide>
<ide> | Name | Type | Description |
<ide><path>website/docs/usage/processing-pipelines.md
<ide> initializing a Language class via [`from_disk`](/api/language#from_disk).
<ide> - nlp = spacy.load('en', tagger=False, entity=False)
<ide> - doc = nlp(u"I don't want parsed", parse=False)
<ide>
<del>+ nlp = spacy.load('en', disable=['ner'])
<del>+ nlp.remove_pipe('parser')
<add>+ nlp = spacy.load("en", disable=["ner"])
<add>+ nlp.remove_pipe("parser")
<ide> + doc = nlp(u"I don't want parsed")
<ide> ```
<ide>
<ide><path>website/docs/usage/saving-loading.md
<ide> solves this with a clear distinction between setting up the instance and loading
<ide> the data.
<ide>
<ide> ```diff
<del>- nlp = spacy.load("en", path="/path/to/data")
<del>+ nlp = spacy.blank("en").from_disk("/path/to/data")
<add>- nlp = spacy.load("en_core_web_sm", path="/path/to/data")
<add>+ nlp = spacy.blank("en_core_web_sm").from_disk("/path/to/data")
<ide> ```
<ide>
<ide> </Infobox> | 4 |
Go | Go | use consistent applylayer in overlayfs | f47d6b9b9de8c567e9e42e12243cbcce99a7bfc7 | <ide><path>daemon/graphdriver/overlay/overlay.go
<ide> import (
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/docker/docker/pkg/chrootarchive"
<ide> "github.com/docker/libcontainer/label"
<ide> )
<ide>
<ide> func (d *Driver) ApplyDiff(id string, parent string, diff archive.ArchiveReader)
<ide> return 0, err
<ide> }
<ide>
<del> if err := archive.ApplyLayer(tmpRootDir, diff); err != nil {
<add> if err := chrootarchive.ApplyLayer(tmpRootDir, diff); err != nil {
<ide> return 0, err
<ide> }
<ide> | 1 |
Javascript | Javascript | add multiple material slots to three editor | 4e651f4827b172960f9ff241515d190ac391f5e3 | <ide><path>editor/js/Editor.js
<ide> Editor.prototype = {
<ide>
<ide> },
<ide>
<add> getObjectMaterial: function ( object, slot ) {
<add>
<add> var material = object.material;
<add>
<add> if( Array.isArray( material ) == true){
<add> var slot = slot | 0;
<add>
<add> if(slot < 0) slot = 0;
<add> else if(slot >= material.length) slot = material.length;
<add>
<add> material = material[ slot ];
<add> }
<add>
<add> return material;
<add>
<add> },
<add>
<add> setObjectMaterial: function ( object, slot, newMaterial ) {
<add>
<add> var material = object.material;
<add>
<add> if( Array.isArray( material ) == true){
<add> var slot = this.materialSlot | 0;
<add>
<add> if(slot < 0) slot = 0;
<add> else if(slot >= material.length) slot = material.length;
<add>
<add> material[ slot ] = newMaterial;
<add> }else
<add> object.material = newMaterial;
<add> },
<add>
<ide> //
<ide>
<ide> select: function ( object ) {
<ide><path>editor/js/Sidebar.Material.js
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> var signals = editor.signals;
<add>
<ide> var currentObject;
<add>
<add> var currentMaterialSlot = 0;
<ide>
<ide> var container = new UI.Panel();
<ide> container.setBorderTop( '0' );
<ide> Sidebar.Material = function ( editor ) {
<ide> // New / Copy / Paste
<ide>
<ide> var copiedMaterial;
<add>
<ide> var managerRow = new UI.Row();
<ide>
<add> // Current material slot
<add>
<add> var materialSlotRow = new UI.Row();
<add>
<add> materialSlotRow.add( new UI.Text( 'Material Slot' ).setWidth( '90px' ) );
<add>
<add> var materialSlotSelect = new UI.Select().setWidth( '170px' ).setFontSize( '12px' ).onChange( update );
<add>
<add> materialSlotRow.add( materialSlotSelect );
<add>
<add> container.add( materialSlotRow );
<add>
<ide> managerRow.add( new UI.Text( '' ).setWidth( '90px' ) );
<add>
<ide> managerRow.add( new UI.Button( 'New' ).onClick( function () {
<ide>
<ide> var material = new THREE[ materialClass.getValue() ]();
<del> editor.execute( new SetMaterialCommand( currentObject, material ), 'New Material: ' + materialClass.getValue() );
<add> editor.execute( new SetMaterialCommand( currentObject, material, currentMaterialSlot ), 'New Material: ' + materialClass.getValue() );
<ide> update();
<ide>
<ide> } ) );
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> copiedMaterial = currentObject.material;
<ide>
<add> if( Array.isArray( copiedMaterial ) == true){
<add>
<add> if( copiedMaterial.length == 0 ) return;
<add>
<add> copiedMaterial = copiedMaterial[ currentMaterialSlot ]
<add> }
<add>
<ide> } ) );
<ide>
<ide> managerRow.add( new UI.Button( 'Paste' ).setMarginLeft( '4px' ).onClick( function () {
<ide>
<ide> if ( copiedMaterial === undefined ) return;
<ide>
<del> editor.execute( new SetMaterialCommand( currentObject, copiedMaterial ), 'Pasted Material: ' + materialClass.getValue() );
<add> editor.execute( new SetMaterialCommand( currentObject, copiedMaterial, currentMaterialSlot ), 'Pasted Material: ' + materialClass.getValue() );
<ide> refreshUI();
<ide> update();
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var materialNameRow = new UI.Row();
<ide> var materialName = new UI.Input().setWidth( '150px' ).setFontSize( '12px' ).onChange( function () {
<ide>
<del> editor.execute( new SetMaterialValueCommand( editor.selected, 'name', materialName.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( editor.selected, 'name', materialName.getValue(), currentMaterialSlot ) );
<ide>
<ide> } );
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> // shading
<ide>
<ide> var materialShadingRow = new UI.Row();
<del> var materialShading = new UI.Select().setOptions( {
<del>
<del> 0: 'No',
<del> 1: 'Flat',
<del> 2: 'Smooth'
<del>
<del> } ).setWidth( '150px' ).setFontSize( '12px' ).onChange( update );
<add> var materialShading = new UI.Checkbox(false).setLeft( '100px' ).onChange( update );
<ide>
<del> materialShadingRow.add( new UI.Text( 'Shading' ).setWidth( '90px' ) );
<add> materialShadingRow.add( new UI.Text( 'Flat Shaded' ).setWidth( '90px' ) );
<ide> materialShadingRow.add( materialShading );
<ide>
<ide> container.add( materialShadingRow );
<ide> Sidebar.Material = function ( editor ) {
<ide> var geometry = object.geometry;
<ide> var material = object.material;
<ide>
<add> var previousSelectedSlot = currentMaterialSlot;
<add>
<add> currentMaterialSlot = materialSlotSelect.getValue() | 0;
<add>
<add> if( currentMaterialSlot != previousSelectedSlot )
<add> refreshUI(true);
<add>
<add> material = editor.getObjectMaterial( currentObject, currentMaterialSlot )
<add>
<ide> var textureWarning = false;
<ide> var objectHasUvs = false;
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> if ( material.uuid !== undefined && material.uuid !== materialUUID.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'uuid', materialUUID.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'uuid', materialUUID.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material instanceof THREE[ materialClass.getValue() ] === false ) {
<ide>
<ide> material = new THREE[ materialClass.getValue() ]();
<ide>
<del> editor.execute( new SetMaterialCommand( currentObject, material ), 'New Material: ' + materialClass.getValue() );
<add> editor.execute( new SetMaterialCommand( currentObject, material, currentMaterialSlot ), 'New Material: ' + materialClass.getValue() );
<ide> // TODO Copy other references in the scene graph
<ide> // keeping name and UUID then.
<ide> // Also there should be means to create a unique
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> if ( material.color !== undefined && material.color.getHex() !== materialColor.getHexValue() ) {
<ide>
<del> editor.execute( new SetMaterialColorCommand( currentObject, 'color', materialColor.getHexValue() ) );
<add> editor.execute( new SetMaterialColorCommand( currentObject, 'color', materialColor.getHexValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.roughness !== undefined && Math.abs( material.roughness - materialRoughness.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'roughness', materialRoughness.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'roughness', materialRoughness.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.metalness !== undefined && Math.abs( material.metalness - materialMetalness.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'metalness', materialMetalness.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'metalness', materialMetalness.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.emissive !== undefined && material.emissive.getHex() !== materialEmissive.getHexValue() ) {
<ide>
<del> editor.execute( new SetMaterialColorCommand( currentObject, 'emissive', materialEmissive.getHexValue() ) );
<add> editor.execute( new SetMaterialColorCommand( currentObject, 'emissive', materialEmissive.getHexValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.specular !== undefined && material.specular.getHex() !== materialSpecular.getHexValue() ) {
<ide>
<del> editor.execute( new SetMaterialColorCommand( currentObject, 'specular', materialSpecular.getHexValue() ) );
<add> editor.execute( new SetMaterialColorCommand( currentObject, 'specular', materialSpecular.getHexValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.shininess !== undefined && Math.abs( material.shininess - materialShininess.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'shininess', materialShininess.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'shininess', materialShininess.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.clearCoat !== undefined && Math.abs( material.clearCoat - materialClearCoat.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'clearCoat', materialClearCoat.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'clearCoat', materialClearCoat.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.clearCoatRoughness !== undefined && Math.abs( material.clearCoatRoughness - materialClearCoatRoughness.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'clearCoatRoughness', materialClearCoatRoughness.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'clearCoatRoughness', materialClearCoatRoughness.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> if ( material.vertexColors !== vertexColors ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'vertexColors', vertexColors ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'vertexColors', vertexColors, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<ide> if ( material.skinning !== undefined && material.skinning !== materialSkinning.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'skinning', materialSkinning.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'skinning', materialSkinning.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var map = mapEnabled ? materialMap.getValue() : null;
<ide> if ( material.map !== map ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'map', map ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'map', map, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var alphaMap = mapEnabled ? materialAlphaMap.getValue() : null;
<ide> if ( material.alphaMap !== alphaMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'alphaMap', alphaMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'alphaMap', alphaMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var bumpMap = bumpMapEnabled ? materialBumpMap.getValue() : null;
<ide> if ( material.bumpMap !== bumpMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'bumpMap', bumpMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'bumpMap', bumpMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.bumpScale !== materialBumpScale.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'bumpScale', materialBumpScale.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'bumpScale', materialBumpScale.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var normalMap = normalMapEnabled ? materialNormalMap.getValue() : null;
<ide> if ( material.normalMap !== normalMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'normalMap', normalMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'normalMap', normalMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var displacementMap = displacementMapEnabled ? materialDisplacementMap.getValue() : null;
<ide> if ( material.displacementMap !== displacementMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'displacementMap', displacementMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'displacementMap', displacementMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.displacementScale !== materialDisplacementScale.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'displacementScale', materialDisplacementScale.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'displacementScale', materialDisplacementScale.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var roughnessMap = roughnessMapEnabled ? materialRoughnessMap.getValue() : null;
<ide> if ( material.roughnessMap !== roughnessMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'roughnessMap', roughnessMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'roughnessMap', roughnessMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var metalnessMap = metalnessMapEnabled ? materialMetalnessMap.getValue() : null;
<ide> if ( material.metalnessMap !== metalnessMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'metalnessMap', metalnessMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'metalnessMap', metalnessMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var specularMap = specularMapEnabled ? materialSpecularMap.getValue() : null;
<ide> if ( material.specularMap !== specularMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'specularMap', specularMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'specularMap', specularMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> if ( material.envMap !== envMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'envMap', envMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'envMap', envMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> if ( material.reflectivity !== reflectivity ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'reflectivity', reflectivity ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'reflectivity', reflectivity, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var lightMap = lightMapEnabled ? materialLightMap.getValue() : null;
<ide> if ( material.lightMap !== lightMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'lightMap', lightMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'lightMap', lightMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var aoMap = aoMapEnabled ? materialAOMap.getValue() : null;
<ide> if ( material.aoMap !== aoMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'aoMap', aoMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'aoMap', aoMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.aoMapIntensity !== materialAOScale.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'aoMapIntensity', materialAOScale.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'aoMapIntensity', materialAOScale.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var emissiveMap = emissiveMapEnabled ? materialEmissiveMap.getValue() : null;
<ide> if ( material.emissiveMap !== emissiveMap ) {
<ide>
<del> editor.execute( new SetMaterialMapCommand( currentObject, 'emissiveMap', emissiveMap ) );
<add> editor.execute( new SetMaterialMapCommand( currentObject, 'emissiveMap', emissiveMap, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var side = parseInt( materialSide.getValue() );
<ide> if ( material.side !== side ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'side', side ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'side', side, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide>
<ide> }
<ide>
<del> if ( material.shading !== undefined ) {
<add> if ( material.flatShading !== undefined ) {
<ide>
<del> var shading = parseInt( materialShading.getValue() );
<del> if ( material.shading !== shading ) {
<add> var flatShading = materialShading.getValue();
<add> if ( material.flatShading != flatShading ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'shading', shading ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'flatShading', flatShading, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> var blending = parseInt( materialBlending.getValue() );
<ide> if ( material.blending !== blending ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'blending', blending ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'blending', blending, currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> }
<ide>
<ide> if ( material.opacity !== undefined && Math.abs( material.opacity - materialOpacity.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'opacity', materialOpacity.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'opacity', materialOpacity.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.transparent !== undefined && material.transparent !== materialTransparent.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'transparent', materialTransparent.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'transparent', materialTransparent.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.alphaTest !== undefined && Math.abs( material.alphaTest - materialAlphaTest.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'alphaTest', materialAlphaTest.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'alphaTest', materialAlphaTest.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> if ( material.wireframe !== undefined && material.wireframe !== materialWireframe.getValue() ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'wireframe', materialWireframe.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'wireframe', materialWireframe.getValue(), currentMaterialSlot) );
<ide>
<ide> }
<ide>
<ide> if ( material.wireframeLinewidth !== undefined && Math.abs( material.wireframeLinewidth - materialWireframeLinewidth.getValue() ) >= 0.01 ) {
<ide>
<del> editor.execute( new SetMaterialValueCommand( currentObject, 'wireframeLinewidth', materialWireframeLinewidth.getValue() ) );
<add> editor.execute( new SetMaterialValueCommand( currentObject, 'wireframeLinewidth', materialWireframeLinewidth.getValue(), currentMaterialSlot ) );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> 'aoMap': materialAOMapRow,
<ide> 'emissiveMap': materialEmissiveMapRow,
<ide> 'side': materialSideRow,
<del> 'shading': materialShadingRow,
<add> 'flatShading': materialShadingRow,
<ide> 'blending': materialBlendingRow,
<ide> 'opacity': materialOpacityRow,
<ide> 'transparent': materialTransparentRow,
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> var material = currentObject.material;
<ide>
<add> if( Array.isArray( material ) == true){
<add>
<add> if( material.length == 0 ) return;
<add>
<add> material = material[0]
<add> }
<add>
<ide> for ( var property in properties ) {
<ide>
<ide> properties[ property ].setDisplay( material[ property ] !== undefined ? '' : 'none' );
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> var material = currentObject.material;
<ide>
<add> var materialArray = []
<add>
<add> if( Array.isArray( material ) == true){
<add>
<add> if( material.length == 0 ){
<add>
<add> currentMaterialSlot = 0;
<add>
<add> materialArray = [undefined];
<add>
<add> }else{
<add>
<add> materialArray = material;
<add>
<add> }
<add>
<add> } else {
<add>
<add> materialArray = [material];
<add>
<add> }
<add>
<add> var slotOptions = {};
<add>
<add> if( ( currentMaterialSlot < 0 ) || ( currentMaterialSlot >= materialArray.length ) ) currentMaterialSlot = 0;
<add>
<add> for( var i=0; i < materialArray.length; i++){
<add>
<add> var material = materialArray[ i ];
<add>
<add> var label = material ? ( material.name == '' ? '[Unnamed]' : material.name ) : '[No Material]';
<add>
<add> slotOptions[i] = '' + (i+1) + ':' + materialArray.length + ' ' + label;
<add> }
<add>
<add> materialSlotSelect.setOptions(slotOptions).setValue( currentMaterialSlot )
<add>
<add> material = editor.getObjectMaterial( currentObject, currentMaterialSlot );
<add>
<add>
<ide> if ( material.uuid !== undefined ) {
<ide>
<ide> materialUUID.setValue( material.uuid );
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> }
<ide>
<del> if ( material.shading !== undefined ) {
<add> if ( material.flatShading !== undefined ) {
<ide>
<del> materialShading.setValue( material.shading );
<add> materialShading.setValue( material.flatShading );
<ide>
<ide> }
<ide>
<ide> Sidebar.Material = function ( editor ) {
<ide> // events
<ide>
<ide> signals.objectSelected.add( function ( object ) {
<add> var hasMaterial = false
<add>
<add> if ( object && object.material ) {
<add> if( ( Array.isArray( object.material ) === false ) || ( object.material.length > 0 ) )
<add> hasMaterial = true;
<add> }
<ide>
<del> if ( object && object.material &&
<del> Array.isArray( object.material ) === false ) {
<add> if( hasMaterial ){
<ide>
<ide> var objectChanged = object !== currentObject;
<ide>
<ide><path>editor/js/commands/SetMaterialColorCommand.js
<ide> * @constructor
<ide> */
<ide>
<del>var SetMaterialColorCommand = function ( object, attributeName, newValue ) {
<add>var SetMaterialColorCommand = function ( object, attributeName, newValue, slot ) {
<ide>
<ide> Command.call( this );
<ide>
<ide> var SetMaterialColorCommand = function ( object, attributeName, newValue ) {
<ide>
<ide> this.object = object;
<ide> this.attributeName = attributeName;
<del> this.oldValue = ( object !== undefined ) ? this.object.material[ this.attributeName ].getHex() : undefined;
<del> this.newValue = newValue;
<add> this.slot = slot | 0;
<add>
<add> var material = this.editor.getObjectMaterial( this.object, this.slot );
<ide>
<add> //this.oldValue = ( object !== undefined ) ? this.object.material[ this.attributeName ].getHex() : undefined;
<add> this.oldValue = ( material !== undefined ) ? material[ this.attributeName ].getHex() : undefined;
<add> this.newValue = newValue;
<add>
<ide> };
<ide>
<ide> SetMaterialColorCommand.prototype = {
<ide>
<ide> execute: function () {
<del>
<del> this.object.material[ this.attributeName ].setHex( this.newValue );
<del> this.editor.signals.materialChanged.dispatch( this.object.material );
<add> var material = this.editor.getObjectMaterial( this.object, this.slot )
<add> material[ this.attributeName ].setHex( this.newValue );
<add> this.editor.signals.materialChanged.dispatch( material );
<ide>
<ide> },
<ide>
<ide> undo: function () {
<add> var material = this.editor.getObjectMaterial( this.object, this.slot )
<ide>
<del> this.object.material[ this.attributeName ].setHex( this.oldValue );
<del> this.editor.signals.materialChanged.dispatch( this.object.material );
<add> material[ this.attributeName ].setHex( this.oldValue );
<add> this.editor.signals.materialChanged.dispatch( material );
<ide>
<ide> },
<ide>
<ide><path>editor/js/commands/SetMaterialCommand.js
<ide> * @constructor
<ide> */
<ide>
<del>var SetMaterialCommand = function ( object, newMaterial ) {
<add>
<add>var SetMaterialCommand = function ( object, newMaterial , slot) {
<ide>
<ide> Command.call( this );
<ide>
<ide> this.type = 'SetMaterialCommand';
<ide> this.name = 'New Material';
<ide>
<ide> this.object = object;
<del> this.oldMaterial = ( object !== undefined ) ? object.material : undefined;
<del> this.newMaterial = newMaterial;
<ide>
<add> this.slot = slot | 0;
<add>
<add> var material = this.editor.getObjectMaterial( this.object, this.slot );
<add>
<add> this.oldMaterial = material;
<add>
<add> this.newMaterial = newMaterial;
<add>
<ide> };
<ide>
<ide> SetMaterialCommand.prototype = {
<ide>
<ide> execute: function () {
<add>
<add> this.editor.setObjectMaterial( this.object, this.slot, this.newMaterial );
<ide>
<del> this.object.material = this.newMaterial;
<ide> this.editor.signals.materialChanged.dispatch( this.newMaterial );
<ide>
<ide> },
<ide>
<ide> undo: function () {
<add>
<add> this.editor.setObjectMaterial( this.object, this.slot, this.oldMaterial );
<ide>
<del> this.object.material = this.oldMaterial;
<ide> this.editor.signals.materialChanged.dispatch( this.oldMaterial );
<ide>
<ide> },
<ide><path>editor/js/commands/SetMaterialValueCommand.js
<ide> * @constructor
<ide> */
<ide>
<del>var SetMaterialValueCommand = function ( object, attributeName, newValue ) {
<add>var SetMaterialValueCommand = function ( object, attributeName, newValue, slot ) {
<ide>
<ide> Command.call( this );
<ide>
<ide> this.type = 'SetMaterialValueCommand';
<ide> this.name = 'Set Material.' + attributeName;
<ide> this.updatable = true;
<add> this.slot = slot;
<ide>
<ide> this.object = object;
<del> this.oldValue = ( object !== undefined ) ? object.material[ attributeName ] : undefined;
<add>
<add> var material = this.editor.getObjectMaterial( this.object, this.slot );
<add>
<add> this.oldValue = ( material !== undefined ) ? material[ attributeName ] : undefined;
<ide> this.newValue = newValue;
<ide> this.attributeName = attributeName;
<ide>
<ide> var SetMaterialValueCommand = function ( object, attributeName, newValue ) {
<ide> SetMaterialValueCommand.prototype = {
<ide>
<ide> execute: function () {
<del>
<del> this.object.material[ this.attributeName ] = this.newValue;
<del> this.object.material.needsUpdate = true;
<add> var material = this.editor.getObjectMaterial( this.object, this.slot );
<add> material[ this.attributeName ] = this.newValue;
<add> material.needsUpdate = true;
<ide> this.editor.signals.objectChanged.dispatch( this.object );
<del> this.editor.signals.materialChanged.dispatch( this.object.material );
<add> this.editor.signals.materialChanged.dispatch( material );
<ide>
<ide> },
<ide>
<ide> undo: function () {
<add> var material = this.editor.getObjectMaterial( this.object, this.slot );
<ide>
<del> this.object.material[ this.attributeName ] = this.oldValue;
<del> this.object.material.needsUpdate = true;
<add> material[ this.attributeName ] = this.oldValue;
<add> material.needsUpdate = true;
<ide> this.editor.signals.objectChanged.dispatch( this.object );
<del> this.editor.signals.materialChanged.dispatch( this.object.material );
<add> this.editor.signals.materialChanged.dispatch( material );
<ide>
<ide> },
<ide> | 5 |
Python | Python | add pre-commit to ignored requirements | ac45c7c045c704ccc1b91e9d3bcb4328c3f3f8ba | <ide><path>spacy/tests/package/test_requirements.py
<ide> def test_build_dependencies():
<ide> "mock",
<ide> "flake8",
<ide> "hypothesis",
<add> "pre-commit",
<ide> ]
<ide> # ignore language-specific packages that shouldn't be installed by all
<ide> libs_ignore_setup = [ | 1 |
Text | Text | add language corrections and change the snippet | 15bc4107827703bed490ccd3bd1ab7368b79bb0c | <ide><path>guide/russian/css/background-opacity/index.md
<ide> localeTitle: Непрозрачность фона
<ide> ---
<ide> ## Непрозрачность фона
<ide>
<del>Свойство opacity указывает непрозрачность / прозрачность элемента, то есть степень видимости содержимого за элементом.
<add>Свойство прозрачности (opacity) указывает на прозрачность/непрозрачность элемента, то есть на степень видимости содержимого за элементом.
<ide>
<del>Свойство opacity может принимать значение от 0.0 до 1.0. Чем ниже значение, тем прозрачнее:
<add>Свойство прозрачности может принимать значение от 0.0 до 1.0. Чем ниже значение, тем больше прозрачность:
<ide>
<ide> Подробнее [здесь](https://www.w3schools.com/css/css_image_transparency.asp)
<ide>
<del>Вы можете выбрать, насколько вы хотите сделать элемент прозрачным. Для достижения уровня прозрачности вам необходимо добавить следующее свойство CSS.
<add>Вы можете выбрать насколько вы хотите сделать элемент прозрачным. Для достижения уровня прозрачности вам необходимо добавить следующее свойство CSS.
<ide>
<ide> **Полностью непрозрачный**
<ide>
<ide> localeTitle: Непрозрачность фона
<ide> }
<ide> ```
<ide>
<del>**полупрозрачный**
<add>**Полупрозрачный**
<ide>
<ide> ```css
<ide> .class-name {
<ide> localeTitle: Непрозрачность фона
<ide> Opacity value can be anything between 0 and 1;
<ide> ```
<ide>
<del>**прозрачный**
<add>**Прозрачный**
<ide>
<ide> ```css
<ide> .class-name {
<ide> localeTitle: Непрозрачность фона
<ide> }
<ide> ```
<ide>
<del>В качестве альтернативы вы можете использовать прозрачное значение rgba следующим образом: \`\` \`CSS
<add>В качестве альтернативы вы можете использовать прозрачное значение rgba следующим образом:
<ide>
<del>.class имя { background-color: rgba (0,0,0, .5); } \`\` \` Приведенный выше пример устанавливает, что фон имеет черный цвет с непрозрачностью 50%. Последним значением значения rgba является альфа-значение. Значение альфа 1 равно 100%, а 0,5 (0,5 для коротких) - 50%. Мы используем этот метод для добавления прозрачности к элементу, не затрагивая содержимое внутри.
<add>```css
<add>
<add>.class-name{
<add> background-color: rgba(0,0,0,.5);
<add> }
<add> ```
<add>В приведенном выше примере, фон имеет черный цвет с прозрачностью 50%. Приведенный выше пример указывает, что фон имеет черный цвет с непрозрачностью 50%. Последним значением значения rgba является альфа-значение. Значение альфа 1 равно 100%, а 0.5 (.5 для краткости) равно 50%. Мы используем этот метод для добавления прозрачности к элементу, не затрагивая содержимое внутри.
<ide>
<ide> [Пример кода для отображения диапазонов непрозрачности фона](https://codepen.io/lvcoulter/full/dVrwmK/)
<ide>
<ide> #### Дополнительная информация:
<ide>
<ide> Для получения дополнительной информации посетите [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) [Свойство CSS прозрачности в CSS-трюках](https://css-tricks.com/almanac/properties/o/opacity/)
<ide>
<del>Поддержка браузера: [caniuse](https://caniuse.com/#search=opacity)
<ide>\ No newline at end of file
<add>Поддержка браузера: [caniuse](https://caniuse.com/#search=opacity) | 1 |
Ruby | Ruby | remove dead code | a63fa4356a9901f6c141811cbfdeb132b19e201d | <ide><path>Library/Homebrew/formula.rb
<ide> def build
<ide> @build ||= BuildOptions.new(ARGV.options_only)
<ide> end
<ide>
<del> def url val=nil, specs={}
<del> if val.nil?
<del> return @stable.url if @stable
<del> return @url if @url
<del> end
<add> def url val, specs={}
<ide> @stable ||= SoftwareSpec.new
<ide> @stable.url(val, specs)
<ide> end | 1 |
PHP | PHP | remove incorrect annotations | 90e206b7f6f5b4b854818ed8b05f25386fe4dc42 | <ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php
<ide> */
<ide> class DateTimeWidgetTest extends TestCase
<ide> {
<del> /**
<del> * @setUp
<del> */
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide><path>tests/test_app/TestApp/Model/Behavior/ValidationBehavior.php
<ide>
<ide> /**
<ide> * Description of ValidationBehavior
<del> *
<del> * @author Robert Pustułka <r.pustulka@robotusers.com>
<ide> */
<ide> class ValidationBehavior extends Behavior
<ide> { | 2 |
Go | Go | fix minor linting issues | f2d49cb7ee7f1abf666682f8e41db8d318e31731 | <ide><path>pkg/system/path_windows_test.go
<ide> import (
<ide> func TestCheckSystemDriveAndRemoveDriveLetter(t *testing.T) {
<ide> // Fails if not C drive.
<ide> _, err := CheckSystemDriveAndRemoveDriveLetter(`d:\`, pathdriver.LocalPathDriver)
<del> if err == nil || (err != nil && err.Error() != "The specified path is not on the system drive (C:)") {
<add> if err == nil || err.Error() != "The specified path is not on the system drive (C:)" {
<ide> t.Fatalf("Expected error for d:")
<ide> }
<ide>
<ide><path>pkg/system/process_windows.go
<ide> func IsProcessAlive(pid int) bool {
<ide> func KillProcess(pid int) {
<ide> p, err := os.FindProcess(pid)
<ide> if err == nil {
<del> p.Kill()
<add> _ = p.Kill()
<ide> }
<ide> } | 2 |
Text | Text | add link for learning resource | 665d59de691a18200eab6a4a6a0ac239b112e511 | <ide><path>guide/english/react-native/state/index.md
<ide> const Button = ({ onPress, children, buttonProps, textProps }) => {
<ide> );
<ide> };
<ide> ```
<add>
<add>#### More Information
<add>
<add>- [Good article about state and props](https://learnreact.design/2017/08/16/components-props-and-state) | 1 |
Javascript | Javascript | fix boolean attributes as per html5 spec | f7949c1c23cc150cbf51155e0e479e26e53a37c4 | <ide><path>src/dom/DOMPropertyOperations.js
<ide> var DOMPropertyOperations = {
<ide> return '';
<ide> }
<ide> var attributeName = DOMProperty.getAttributeName[name];
<add> if (DOMProperty.hasBooleanValue[name]) {
<add> return escapeTextForBrowser(attributeName);
<add> }
<ide> return processAttributeNameAndPrefix(attributeName) +
<ide> escapeTextForBrowser(value) + '"';
<ide> } else if (DOMProperty.isCustomAttribute(name)) {
<ide><path>src/dom/__tests__/DOMPropertyOperations-test.js
<ide> describe('DOMPropertyOperations', function() {
<ide> expect(DOMPropertyOperations.createMarkupForProperty(
<ide> 'checked',
<ide> 'simple'
<del> )).toBe('checked="simple"');
<add> )).toBe('checked');
<ide>
<ide> expect(DOMPropertyOperations.createMarkupForProperty(
<ide> 'checked',
<ide> true
<del> )).toBe('checked="true"');
<add> )).toBe('checked');
<ide>
<ide> expect(DOMPropertyOperations.createMarkupForProperty(
<ide> 'checked', | 2 |
Text | Text | add v3.10.0-beta.5 to changelog | 642702dd726420f3cb5a8f4622662aac4df15e1c | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.10.0-beta.5 (April 29, 2019)
<add>
<add>- [#17938](https://github.com/emberjs/ember.js/pull/17938) [BUGFIX] Expose mechanism to detect if a property is a computed
<add>- [#17974](https://github.com/emberjs/ember.js/pull/17974) [BUGFIX] Ensure inheritable observers on object proxies are string based
<add>
<ide> ### v3.10.0-beta.4 (April 22, 2019)
<ide>
<ide> - [#17930](https://github.com/emberjs/ember.js/pull/17930) [BUGFIX] Update assertion for events in tagless component to include method names | 1 |
Python | Python | add xml parser | 0632e946f977609ca6d6f4272f02c72dee1f49be | <ide><path>djangorestframework/parsers.py
<ide> from djangorestframework.compat import yaml
<ide> from djangorestframework.response import ErrorResponse
<ide> from djangorestframework.utils.mediatypes import media_type_matches
<add>from xml.etree import ElementTree as ET
<add>import datetime
<add>import decimal
<ide>
<ide>
<ide> __all__ = (
<ide> 'FormParser',
<ide> 'MultiPartParser',
<ide> 'YAMLParser',
<add> 'XMLParser'
<ide> )
<ide>
<ide>
<ide> def parse(self, stream):
<ide> raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
<ide> {'detail': 'multipart parse error - %s' % unicode(exc)})
<ide> return django_parser.parse()
<add>
<add>
<add>class XMLParser(BaseParser):
<add> """
<add> XML parser.
<add> """
<add>
<add> media_type = 'application/xml'
<add>
<add> def parse(self, stream):
<add> """
<add> Returns a 2-tuple of `(data, files)`.
<add>
<add> `data` will simply be a string representing the body of the request.
<add> `files` will always be `None`.
<add> """
<add> data = {}
<add> tree = ET.parse(stream)
<add> for child in tree.getroot().getchildren():
<add> data[child.tag] = self._type_convert(child.text)
<add>
<add> return (data, None)
<add>
<add> def _type_convert(self, value):
<add> """
<add> Converts the value returned by the XMl parse into the equivalent
<add> Python type
<add> """
<add> if value is None:
<add> return value
<add>
<add> try:
<add> return datetime.datetime.strptime(value,'%Y-%m-%d %H:%M:%S')
<add> except ValueError:
<add> pass
<add>
<add> try:
<add> return int(value)
<add> except ValueError:
<add> pass
<add>
<add> try:
<add> return decimal.Decimal(value)
<add> except decimal.InvalidOperation:
<add> pass
<add>
<add> return value
<add>
<ide>
<ide> DEFAULT_PARSERS = ( JSONParser,
<ide> FormParser,
<del> MultiPartParser )
<add> MultiPartParser,
<add> XMLParser
<add> )
<ide>
<ide> if YAMLParser:
<del> DEFAULT_PARSERS += ( YAMLParser, )
<add> DEFAULT_PARSERS += ( YAMLParser, )
<ide>\ No newline at end of file
<ide><path>djangorestframework/tests/parsers.py
<ide> from django import forms
<ide> from django.test import TestCase
<ide> from djangorestframework.parsers import FormParser
<add>from djangorestframework.parsers import XMLParser
<add>import datetime
<ide>
<ide> class Form(forms.Form):
<ide> field1 = forms.CharField(max_length=3)
<ide> def test_parse(self):
<ide> (data, files) = parser.parse(stream)
<ide>
<ide> self.assertEqual(Form(data).is_valid(), True)
<add>
<add>
<add>class TestXMLParser(TestCase):
<add> def setUp(self):
<add> self.input = StringIO(
<add> '<?xml version="1.0" encoding="utf-8"?>'
<add> '<root>'
<add> '<field_a>121.0</field_a>'
<add> '<field_b>dasd</field_b>'
<add> '<field_c></field_c>'
<add> '<field_d>2011-12-25 12:45:00</field_d>'
<add> '</root>'
<add> )
<add> self.data = {
<add> 'field_a': 121,
<add> 'field_b': 'dasd',
<add> 'field_c': None,
<add> 'field_d': datetime.datetime(2011, 12, 25, 12, 45, 00)
<add>
<add> }
<add>
<add> def test_parse(self):
<add> parser = XMLParser(None)
<add> (data, files) = parser.parse(self.input)
<add> self.assertEqual(data, self.data)
<ide>\ No newline at end of file
<ide><path>djangorestframework/tests/renderers.py
<ide>
<ide> from djangorestframework import status
<ide> from djangorestframework.compat import View as DjangoView
<del>from djangorestframework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer
<del>from djangorestframework.parsers import JSONParser, YAMLParser
<add>from djangorestframework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer,\
<add> XMLRenderer
<add>from djangorestframework.parsers import JSONParser, YAMLParser, XMLParser
<ide> from djangorestframework.mixins import ResponseMixin
<ide> from djangorestframework.response import Response
<ide> from djangorestframework.utils.mediatypes import add_media_type_param
<ide>
<ide> from StringIO import StringIO
<add>import datetime
<add>from decimal import Decimal
<ide>
<ide> DUMMYSTATUS = status.HTTP_200_OK
<ide> DUMMYCONTENT = 'dummycontent'
<ide> def test_render_and_parse(self):
<ide>
<ide> content = renderer.render(obj, 'application/yaml')
<ide> (data, files) = parser.parse(StringIO(content))
<del> self.assertEquals(obj, data)
<ide>\ No newline at end of file
<add> self.assertEquals(obj, data)
<add>
<add>
<add>class XMLRendererTestCase(TestCase):
<add> """
<add> Tests specific to the JSON Renderer
<add> """
<add>
<add> def test_render_string(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({'field': 'astring'}, 'application/xml')
<add> self.assertXMLContains(content, '<field>astring</field>')
<add>
<add> def test_render_integer(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({'field': 111}, 'application/xml')
<add> self.assertXMLContains(content, '<field>111</field>')
<add>
<add> def test_render_datetime(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({
<add> 'field': datetime.datetime(2011, 12, 25, 12, 45, 00)
<add> }, 'application/xml')
<add> self.assertXMLContains(content, '<field>2011-12-25 12:45:00</field>')
<add>
<add> def test_render_float(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({'field': 123.4}, 'application/xml')
<add> self.assertXMLContains(content, '<field>123.4</field>')
<add>
<add> def test_render_decimal(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({'field': Decimal('111.2')}, 'application/xml')
<add> self.assertXMLContains(content, '<field>111.2</field>')
<add>
<add> def test_render_none(self):
<add> """
<add> Test XML rendering.
<add> """
<add> renderer = XMLRenderer(None)
<add> content = renderer.render({'field': None}, 'application/xml')
<add> self.assertXMLContains(content, '<field></field>')
<add>
<add>
<add> def assertXMLContains(self, xml, string):
<add> self.assertTrue(xml.startswith('<?xml version="1.0" encoding="utf-8"?>\n<root>'))
<add> self.assertTrue(xml.endswith('</root>'))
<add> self.assertTrue(string in xml, '%r not in %r' % (string, xml))
<ide>\ No newline at end of file
<ide><path>djangorestframework/utils/__init__.py
<ide> def _to_xml(self, xml, data):
<ide> xml.startElement(key, {})
<ide> self._to_xml(xml, value)
<ide> xml.endElement(key)
<add>
<add> elif data is None:
<add> # Don't output any value
<add> pass
<ide>
<ide> else:
<ide> xml.characters(smart_unicode(data))
<ide> def dict2xml(self, data):
<ide> return stream.getvalue()
<ide>
<ide> def dict2xml(input):
<del> return XMLRenderer().dict2xml(input)
<add> return XMLRenderer().dict2xml(input)
<ide>\ No newline at end of file | 4 |
Text | Text | update habtm documentation in guides | ae83b01b1988d85e2370a53b8c41f5be1a15e946 | <ide><path>guides/source/association_basics.md
<ide> The `collection.delete` method removes one or more objects from the collection b
<ide> @part.assemblies.delete(@assembly1)
<ide> ```
<ide>
<del>WARNING: This does not trigger callbacks on the join records.
<del>
<ide> ##### `collection.destroy(object, ...)`
<ide>
<del>The `collection.destroy` method removes one or more objects from the collection by running `destroy` on each record in the join table, including running callbacks. This does not destroy the objects.
<add>The `collection.destroy` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
<ide>
<ide> ```ruby
<ide> @part.assemblies.destroy(@assembly1) | 1 |
Ruby | Ruby | remove testing hwia serialization for old psych | 458f4c48ec7095dd1945306fad3d9c35e6f8a70e | <ide><path>activesupport/test/hash_with_indifferent_access_test.rb
<ide> def initialize(*)
<ide>
<ide> yaml_output = klass.new.to_yaml
<ide>
<del> # `hash-with-ivars` was introduced in 2.0.9 (https://git.io/vyUQW)
<del> if Gem::Version.new(Psych::VERSION) >= Gem::Version.new("2.0.9")
<del> assert_includes yaml_output, "hash-with-ivars"
<del> assert_includes yaml_output, "@foo: bar"
<del> else
<del> assert_includes yaml_output, "hash"
<del> end
<add> assert_includes yaml_output, "hash-with-ivars"
<add> assert_includes yaml_output, "@foo: bar"
<ide> end
<ide>
<ide> def test_should_use_default_proc_for_unknown_key | 1 |
Go | Go | fix invalid usage of reflect.sliceheader | c208f03fbddb4355729c3225bb2550c4d54a2c5e | <ide><path>pkg/devicemapper/devmapper_wrapper.go
<ide> func dmTaskGetDepsFct(task *cdmTask) *Deps {
<ide> }
<ide>
<ide> // golang issue: https://github.com/golang/go/issues/11925
<del> hdr := reflect.SliceHeader{
<del> Data: uintptr(unsafe.Pointer(uintptr(unsafe.Pointer(Cdeps)) + unsafe.Sizeof(*Cdeps))),
<del> Len: int(Cdeps.count),
<del> Cap: int(Cdeps.count),
<del> }
<del> devices := *(*[]C.uint64_t)(unsafe.Pointer(&hdr))
<add> var devices []C.uint64_t
<add> devicesHdr := (*reflect.SliceHeader)(unsafe.Pointer(&devices))
<add> devicesHdr.Data = uintptr(unsafe.Pointer(uintptr(unsafe.Pointer(Cdeps)) + unsafe.Sizeof(*Cdeps)))
<add> devicesHdr.Len = int(Cdeps.count)
<add> devicesHdr.Cap = int(Cdeps.count)
<ide>
<ide> deps := &Deps{
<ide> Count: uint32(Cdeps.count), | 1 |
Javascript | Javascript | wrap the hashchange event in an ember.run | 03cebf38d091604046b0f7704804fe54630bdab9 | <ide><path>packages/ember-routing/lib/location/hash_location.js
<ide> Ember.HashLocation = Ember.Object.extend({
<ide> var guid = Ember.guidFor(this);
<ide>
<ide> Ember.$(window).bind('hashchange.ember-location-'+guid, function() {
<del> var path = location.hash.substr(1);
<del> if (get(self, 'lastSetURL') === path) { return; }
<add> Ember.run(function() {
<add> var path = location.hash.substr(1);
<add> if (get(self, 'lastSetURL') === path) { return; }
<ide>
<del> set(self, 'lastSetURL', null);
<add> set(self, 'lastSetURL', null);
<ide>
<del> callback(location.hash.substr(1));
<add> callback(location.hash.substr(1));
<add> });
<ide> });
<ide> },
<ide> | 1 |
Ruby | Ruby | use preferred_gcc instead of gcc | 0a292c7041d4497d51259882fc7e44892e875133 | <ide><path>Library/Homebrew/compilers.rb
<ide> def compiler
<ide> raise CompilerSelectionError, formula
<ide> end
<ide>
<del> private
<del>
<ide> sig { returns(String) }
<del> def preferred_gcc
<add> def self.preferred_gcc
<ide> "gcc"
<ide> end
<ide>
<add> private
<add>
<ide> def gnu_gcc_versions
<ide> # prioritize gcc version provided by gcc formula.
<del> v = Formulary.factory(preferred_gcc).version.to_s.slice(/\d+/)
<add> v = Formulary.factory(CompilerSelector.preferred_gcc).version.to_s.slice(/\d+/)
<ide> GNU_GCC_VERSIONS - [v] + [v] # move the version to the end of the list
<ide> rescue FormulaUnavailableError
<ide> GNU_GCC_VERSIONS
<ide><path>Library/Homebrew/extend/os/linux/compilers.rb
<ide>
<ide> class CompilerSelector
<ide> sig { returns(String) }
<del> def preferred_gcc
<add> def self.preferred_gcc
<ide> # gcc-5 is the lowest gcc version we support on Linux.
<ide> # gcc-5 is the default gcc in Ubuntu 16.04 (used for our CI)
<ide> "gcc@5"
<ide><path>Library/Homebrew/extend/os/linux/keg_relocate.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<add>require "compilers"
<add>
<ide> class Keg
<ide> def relocate_dynamic_linkage(relocation)
<ide> # Patching the dynamic linker of glibc breaks it.
<ide> def self.relocation_formulae
<ide> def self.bottle_dependencies
<ide> @bottle_dependencies ||= begin
<ide> formulae = relocation_formulae
<del> gcc = Formula["gcc"]
<add> gcc = Formulary.factory(CompilerSelector.preferred_gcc)
<ide> if !Homebrew::EnvConfig.force_homebrew_on_linux? &&
<ide> DevelopmentTools.non_apple_gcc_version("gcc") < gcc.version.to_i
<ide> formulae += gcc.recursive_dependencies.map(&:name)
<ide><path>Library/Homebrew/extend/os/linux/linkage_checker.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<add>require "compilers"
<add>
<ide> class LinkageChecker
<ide> # Libraries provided by glibc and gcc.
<ide> SYSTEM_LIBRARY_ALLOWLIST = %w[
<ide> def check_dylibs(rebuild_cache:)
<ide> @unwanted_system_dylibs = @system_dylibs.reject do |s|
<ide> SYSTEM_LIBRARY_ALLOWLIST.include? File.basename(s)
<ide> end
<del> @undeclared_deps -= ["gcc", "glibc"]
<add> @undeclared_deps -= [CompilerSelector.preferred_gcc, "glibc"]
<ide> end
<ide> end
<ide><path>Library/Homebrew/extend/os/linux/system_config.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<add>require "compilers"
<ide> require "os/linux/glibc"
<ide> require "system_command"
<ide>
<ide> def dump_verbose_config(out = $stdout)
<ide> out.puts "Host glibc: #{host_glibc_version}"
<ide> out.puts "/usr/bin/gcc: #{host_gcc_version}"
<ide> out.puts "/usr/bin/ruby: #{host_ruby_version}" if RUBY_PATH != HOST_RUBY_PATH
<del> ["glibc", "gcc", "xorg"].each do |f|
<add> ["glibc", CompilerSelector.preferred_gcc, "xorg"].each do |f|
<ide> out.puts "#{f}: #{formula_linked_version(f)}"
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/formula_installer_bottle_spec.rb
<ide> def temporarily_install_bottle(formula)
<ide>
<ide> stub_formula_loader formula
<ide> stub_formula_loader formula("gcc") { url "gcc-1.0" }
<add> stub_formula_loader formula("gcc@5") { url "gcc-5.0" }
<ide> stub_formula_loader formula("patchelf") { url "patchelf-1.0" }
<ide> allow(Formula["patchelf"]).to receive(:latest_version_installed?).and_return(true)
<ide>
<ide><path>Library/Homebrew/test/formulary_spec.rb
<ide> class Wrong#{described_class.class_s(formula_name)} < Formula
<ide> before do
<ide> allow(described_class).to receive(:loader_for).and_call_original
<ide> stub_formula_loader formula("gcc") { url "gcc-1.0" }
<add> stub_formula_loader formula("gcc@5") { url "gcc-5.0" }
<ide> stub_formula_loader formula("patchelf") { url "patchelf-1.0" }
<ide> allow(Formula["patchelf"]).to receive(:latest_version_installed?).and_return(true)
<ide> end | 7 |
Mixed | Text | use correct path in documentation | 1a61496ae5945c0412a3e1692c5909635fb9f27b | <ide><path>guides/source/4_2_release_notes.md
<ide> Please refer to the [Changelog][railties] for detailed changes.
<ide> url: http://localhost:3001
<ide> namespace: my_app_development
<ide>
<del> # config/production.rb
<add> # config/environments/production.rb
<ide> Rails.application.configure do
<ide> config.middleware.use ExceptionNotifier, config_for(:exception_notification)
<ide> end
<ide><path>guides/source/asset_pipeline.md
<ide> your CDN server, you need to tell browsers to use your CDN to grab assets
<ide> instead of your Rails server directly. You can do this by configuring Rails to
<ide> set your CDN as the asset host instead of using a relative path. To set your
<ide> asset host in Rails, you need to set `config.action_controller.asset_host` in
<del>`config/production.rb`:
<add>`config/environments/production.rb`:
<ide>
<ide> ```ruby
<ide> config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
<ide><path>railties/lib/rails/application.rb
<ide> def message_verifier(verifier_name)
<ide> # url: http://localhost:3001
<ide> # namespace: my_app_development
<ide> #
<del> # # config/production.rb
<add> # # config/environments/production.rb
<ide> # Rails.application.configure do
<ide> # config.middleware.use ExceptionNotifier, config_for(:exception_notification)
<ide> # end | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.